1const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/uploadMedia-BPkFDiJH.js","assets/api-CyvozDRd.js"])))=>i.map(i=>d[i]); 2import{c as ge,_ as Y,u as ps,g as js,B as w,a as xs,b as Pe,C as lt,T as Ns,X as Me,M as ws,d as ks,Y as _s,L as Cs,I as Ss,e as Ts,F as Zt,f as Es}from"./index-CVuSjWCq.js";import{j as e,a as m}from"./query-vendor-BB0JUlq_.js";import{s as As,g as Ps}from"./unsplash-gQ5iVEsL.js";import{a as qt}from"./schedule-D1M9yW21.js";import{C as Fs}from"./card-COxgaMnN.js";import{apiFetch as we}from"./api-CyvozDRd.js";import{Z as Rs,R as Is}from"./zoom-in-Ds9-Y-UM.js";import{R as Bt,a as At}from"./radio-group-X0hhJcQh.js";import{L as Ge}from"./label-CuOi8NYy.js";import{C as xt}from"./calendar-BGqwoozq.js";import{U as We,E as Os}from"./user-B99NGEGJ.js";import{M as ft,P as Ls}from"./phone-D3GMUtg_.js";import{B as Ds,C as fs,I as Ms}from"./input-C0u5xVbq.js";import{M as It,r as Ot}from"./index-BPI0DfIe.js";import{D as $s}from"./DiscussionFeed-DgfaxC1r.js";import{C as zs}from"./ChatsPanel-fiT1dbtl.js";import{N as Us}from"./NotificationBell-DrucT7Pa.js";import{d as Vs}from"./react-vendor-BIjsaQ6L.js";import{C as Zs}from"./chevron-down-O6I9_XNE.js";import{S as qs}from"./search-U2F7YYEh.js";import"./ui-vendor-CwH6wFZJ.js";const Bs=[["path",{d:"M6 12h9a4 4 0 0 1 0 8H7a1 1 0 0 1-1-1V5a1 1 0 0 1 1-1h7a4 4 0 0 1 0 8",key:"mg9rjx"}]],Hs=ge("bold",Bs);const Gs=[["path",{d:"M21.801 10A10 10 0 1 1 17 3.335",key:"yps3ct"}],["path",{d:"m9 11 3 3L22 4",key:"1pflzl"}]],Ws=ge("circle-check-big",Gs);const Ys=[["path",{d:"m16 18 6-6-6-6",key:"eg8j8"}],["path",{d:"m8 6-6 6 6 6",key:"ppft3o"}]],Js=ge("code",Ys);const Qs=[["ellipse",{cx:"12",cy:"5",rx:"9",ry:"3",key:"msslwz"}],["path",{d:"M3 5V19A9 3 0 0 0 21 19V5",key:"1wlel7"}],["path",{d:"M3 12A9 3 0 0 0 21 12",key:"mv7ke4"}]],Ks=ge("database",Qs);const Xs=[["path",{d:"M15 3h6v6",key:"1q9fwt"}],["path",{d:"M10 14 21 3",key:"gplh6r"}],["path",{d:"M18 13v6a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V8a2 2 0 0 1 2-2h6",key:"a6xqqp"}]],ea=ge("external-link",Xs);const ta=[["path",{d:"M4 12h8",key:"17cfdx"}],["path",{d:"M4 18V6",key:"1rz3zl"}],["path",{d:"M12 18V6",key:"zqpxq5"}],["path",{d:"M21 18h-4c0-4 4-3 4-6 0-1.5-2-2.5-4-1",key:"9jr5yi"}]],sa=ge("heading-2",ta);const aa=[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",ry:"2",key:"1m3agn"}],["circle",{cx:"9",cy:"9",r:"2",key:"af1f0g"}],["path",{d:"m21 15-3.086-3.086a2 2 0 0 0-2.828 0L6 21",key:"1xmnt7"}]],ra=ge("image",aa);const na=[["line",{x1:"19",x2:"10",y1:"4",y2:"4",key:"15jd3p"}],["line",{x1:"14",x2:"5",y1:"20",y2:"20",key:"bu0au3"}],["line",{x1:"15",x2:"9",y1:"4",y2:"20",key:"uljnxc"}]],ia=ge("italic",na);const oa=[["path",{d:"M10 13a5 5 0 0 0 7.54.54l3-3a5 5 0 0 0-7.07-7.07l-1.72 1.71",key:"1cjeqo"}],["path",{d:"M14 11a5 5 0 0 0-7.54-.54l-3 3a5 5 0 0 0 7.07 7.07l1.71-1.71",key:"19qd67"}]],la=ge("link",oa);const da=[["path",{d:"M10 12h11",key:"6m4ad9"}],["path",{d:"M10 18h11",key:"11hvi2"}],["path",{d:"M10 6h11",key:"c7qv1k"}],["path",{d:"M4 10h2",key:"16xx2s"}],["path",{d:"M4 6h1v4",key:"cnovpq"}],["path",{d:"M6 18H4c0-1 2-2 2-3s-1-1.5-2-1",key:"m9a95d"}]],ca=ge("list-ordered",da);const ua=[["path",{d:"M3 12h.01",key:"nlz23k"}],["path",{d:"M3 18h.01",key:"1tta3j"}],["path",{d:"M3 6h.01",key:"1rqtza"}],["path",{d:"M8 12h13",key:"1za7za"}],["path",{d:"M8 18h13",key:"1lx6n3"}],["path",{d:"M8 6h13",key:"ik3vkj"}]],ma=ge("list",ua);const ha=[["path",{d:"M13 21h8",key:"1jsn5i"}],["path",{d:"M21.174 6.812a1 1 0 0 0-3.986-3.987L3.842 16.174a2 2 0 0 0-.5.83l-1.321 4.352a.5.5 0 0 0 .623.622l4.353-1.32a2 2 0 0 0 .83-.497z",key:"1a8usu"}]],pa=ge("pen-line",ha);const xa=[["path",{d:"M5 12h14",key:"1ays0h"}],["path",{d:"M12 5v14",key:"s699le"}]],fa=ge("plus",xa);const ga=[["path",{d:"M16 3a2 2 0 0 0-2 2v6a2 2 0 0 0 2 2 1 1 0 0 1 1 1v1a2 2 0 0 1-2 2 1 1 0 0 0-1 1v2a1 1 0 0 0 1 1 6 6 0 0 0 6-6V5a2 2 0 0 0-2-2z",key:"rib7q0"}],["path",{d:"M5 3a2 2 0 0 0-2 2v6a2 2 0 0 0 2 2 1 1 0 0 1 1 1v1a2 2 0 0 1-2 2 1 1 0 0 0-1 1v2a1 1 0 0 0 1 1 6 6 0 0 0 6-6V5a2 2 0 0 0-2-2z",key:"1ymkrd"}]],va=ge("quote",ga);
2const ba=[["path",{d:"M8 19H5c-1 0-2-1-2-2V7c0-1 1-2 2-2h3",key:"lubmu8"}],["path",{d:"M16 5h3c1 0 2 1 2 2v10c0 1-1 2-2 2h-3",key:"1ag34g"}],["line",{x1:"12",x2:"12",y1:"4",y2:"20",key:"1tx1rr"}]],ya=ge("square-split-horizontal",ba);const ja=[["path",{d:"M10 11v6",key:"nco0om"}],["path",{d:"M14 11v6",key:"outv1u"}],["path",{d:"M19 6v14a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2V6",key:"miytrc"}],["path",{d:"M3 6h18",key:"d0wm0j"}],["path",{d:"M8 6V4a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v2",key:"e791ji"}]],Na=ge("trash-2",ja),Je={async list(){const{apiFetch:a}=await Y(async()=>{const{apiFetch:t}=await import("./api-CyvozDRd.js");return{apiFetch:t}},[]);try{const t=await a("/api/admin/students");return Array.isArray(t)?t:t&&t.rows||[]}catch(t){return console.error("students.list error",t),[]}},async create(a){const{apiFetch:t}=await Y(async()=>{const{apiFetch:r}=await import("./api-CyvozDRd.js");return{apiFetch:r}},[]);return await t("/api/admin/students",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(a)})},async update(a,t){const{apiFetch:s}=await Y(async()=>{const{apiFetch:n}=await import("./api-CyvozDRd.js");return{apiFetch:n}},[]);return await s(`/api/admin/students/${a}`,{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify(t)})},async remove(a){if(!a)throw new Error("Missing student id");const{apiFetch:t}=await Y(async()=>{const{apiFetch:r}=await import("./api-CyvozDRd.js");return{apiFetch:r}},[]);return await t(`/api/admin/students/${a}`,{method:"DELETE"})}};function wa({mode:a,setMode:t,compact:s}){const r=ps(),n=a??r.mode,i=js(),l=n==="dark"?"dark":"";return s?e.jsxs("div",{className:`rounded-md overflow-hidden border bg-card ${l} w-full`,children:[e.jsxs("div",{className:"p-3 text-center",children:[e.jsx("div",{className:"text-sm text-foreground/70",children:"Preview"}),e.jsx("h3",{className:"mt-2 text-lg font-semibold text-foreground",children:i.siteTitle}),e.jsx("p",{className:"mt-1 text-sm text-white/70 dark:text-foreground/70",children:i.heroHeading})]}),e.jsx("div",{className:"px-4 pb-4",children:e.jsx("div",{className:"bg-muted rounded-md p-3 text-center",children:e.jsx("div",{className:"text-base font-semibold text-foreground",children:i.ctaPrimary})})})]}):e.jsxs("div",{className:`min-h-[50vh] rounded-lg overflow-hidden border bg-card ${l}`,children:[e.jsxs("header",{className:"px-6 py-3 border-b bg-card flex items-center justify-between",children:[e.jsx("div",{className:"font-bold text-lg text-foreground",children:i.siteTitle}),e.jsxs("nav",{className:"hidden sm:flex gap-3 text-sm text-foreground/80",children:[e.jsx("span",{children:"Lessons"}),e.jsx("span",{children:"About"}),e.jsx("span",{children:"Contact"})]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(w,{size:"sm",variant:"outline",children:"Book"}),e.jsx("a",{href:`tel:${i.phone}`,className:"inline-block",children:e.jsx(w,{size:"sm",variant:"default",children:"Call"})})]})]}),e.jsx("section",{className:"hero-bg py-12",children:e.jsxs("div",{className:"container mx-auto grid grid-cols-1 lg:grid-cols-12 gap-8 items-center",children:[e.jsxs("div",{className:"lg:col-span-7 text-foreground max-w-2xl",style:{textShadow:"0 1px 2px rgba(0,0,0,0.6)"},children:[e.jsx("div",{className:"inline-flex items-center gap-3 rounded-full bg-white/10 px-3 py-1 text-sm",children:"West Lothianâs award-winning tuition"}),e.jsx("h1",{className:"mt-6 text-2xl md:text-3xl font-extrabold leading-tight",children:i.heroHeading}),e.jsx("p",{className:"mt-4 text-base text-white/90 dark:text-foreground/90",children:i.heroSubheading}),e.jsxs("div",{className:"mt-6 flex flex-col sm:flex-row gap-3",children:[e.jsx(w,{size:"lg",variant:"gradient",children:i.ctaPrimary}),e.jsx(w,{size:"lg",variant:"outline",children:i.ctaSecondary})]})]}),e.jsx("aside",{className:"lg:col-span-5",children:e.jsxs("div",{className:"bg-card rounded-xl p-4 shadow-lg max-w-md mx-auto",children:[e.jsx("h3",{className:"text-lg font-semibold",children:"Book a free trial"}),e.jsx("p",{className:"text-sm text-foreground/70 mt-1",children:"No commitment â try a 30 minute lesson."}),e.jsxs("div",{className:"mt-3 grid gap-2",children:[e.jsx("input",{className:"h-10 rounded-md border px-3",placeholder:"Name"}),e.jsx("input",{className:"h-10 rounded-md border px-3",placeholder:"Email"}),e.jsx(w,{children:"Request"})]})]})})]})}),e.jsx("section",{className:"container mx-auto py-6",children:e.jsxs("div",{className:"p-4 bg-muted rounded-lg",children:[e.jsx("h2",{className:"text-xl font-bold text-foreground",children:"Programs"}
2),e.jsx("p",{className:"mt-2 text-foreground/70 max-w-2xl",children:i.programsIntro}),e.jsx("div",{className:"mt-4 grid grid-cols-2 sm:grid-cols-4 gap-3",children:[{title:"Guitar",img:"https://static.wixstatic.com/media/11062b_5a22f499b68b4cb4bd26d6c7b59b005f~mv2.jpg"},{title:"Singing",img:"https://static.wixstatic.com/media/7bc411_238d51c0e12341719cb19ee6ed9c56a5~mv2.jpeg"},{title:"Piano",img:"https://static.wixstatic.com/media/11062b_d1a6434bf6ad4d508d7c3e0d5a5c4e95~mv2.jpg"},{title:"Drums",img:"https://images.unsplash.com/photo-1519892300165-cb5542fb47c7?w=800&auto=format&fit=crop"}].map(c=>e.jsxs("div",{className:"rounded-lg overflow-hidden border bg-card shadow-sm",children:[e.jsx("img",{src:c.img,alt:c.title,className:"h-20 w-full object-cover"}),e.jsx("div",{className:"p-2 bg-card",children:e.jsx("h3",{className:"font-semibold text-foreground",children:c.title})})]},c.title))})]})}),e.jsx("footer",{className:"px-4 py-3 border-t bg-card text-sm text-foreground/70",children:e.jsxs("div",{className:"container mx-auto",children:["© ",new Date().getFullYear()," ",i.siteTitle]})})]})}const Ht=new Set(["admin","teacher"]);function ka(a){try{const t=new Date(a);return Number.isNaN(t.getTime())?a:t.toLocaleString()}catch{return a}}function _a({meta:a}){return m.useMemo(()=>!a||typeof a!="object"?!1:Object.keys(a).length>0,[a])?e.jsx("pre",{className:"mt-2 whitespace-pre-wrap rounded-md bg-muted/40 p-2 text-xs text-foreground/80",children:JSON.stringify(a,null,2)}):e.jsx("div",{className:"text-xs text-foreground/60",children:"No additional metadata"})}function Ca(){const{user:a}=xs(),{toast:t}=Pe(),[s,r]=m.useState([]),[n,i]=m.useState(""),[l,c]=m.useState(""),[u,x]=m.useState(""),[p,v]=m.useState(""),[y,I]=m.useState(""),[U,V]=m.useState(!1),[L,G]=m.useState(!1),[W,ne]=m.useState(null),[E,d]=m.useState(!1),C=m.useCallback(async()=>{try{const{apiFetch:A}=await Y(async()=>{const{apiFetch:N}=await import("./api-CyvozDRd.js");return{apiFetch:N}},[]),te=await A("/api/admin/audit-logs");if(!Array.isArray(te)){r([]);return}const S=te.map(N=>{const oe=N&&typeof N.meta=="object"&&N.meta!==null?N.meta:{},_e=N?.displayName||N?.username||N?.email||"System";return{id:String(N.id),created_at:N.created_at,action:N.action,meta:oe,role:N.role,displayName:_e,targetDisplayName:N?.targetDisplayName??null}});r(S)}catch(A){console.error(A),t({title:"Unable to load audit logs",description:"Please try again in a moment.",variant:"destructive"})}},[t]);m.useEffect(()=>{C()},[C]),m.useEffect(()=>{if(!a||n.trim())return;const A=a.username||a.email;A&&i(A)},[a,n]),m.useEffect(()=>{const A=s.find(te=>te.action==="admin:data-cleanup-triggered");if(A?.meta){const te=A.meta;te.stats&&ne(te.stats)}},[s]);const k=s.filter(A=>Ht.has((A.role??"").toLowerCase())),b=s.filter(A=>!Ht.has((A.role??"").toLowerCase())),F=A=>{c(""),x(""),v(""),I(""),typeof A=="string"?i(A):(a?.username||a?.email)&&i(a.username||a.email)},T=async A=>{A.preventDefault();const te=n.trim(),S=u.trim();if(!te){t({title:"Identifier required",description:"Enter your current username or email.",variant:"destructive"});return}if(!l){t({title:"Current password required",description:"Enter your existing password to confirm changes.",variant:"destructive"});return}if(!S&&!p){t({title:"Nothing to update",description:"Provide a new username or a new password.",variant:"destructive"});return}if(p&&p!==y){t({title:"Passwords do not match",description:"Confirm password must match the new password.",variant:"destructive"});return}const N={identifier:te,currentPassword:l};S&&(N.newUsername=S),p&&(N.newPassword=p);try{V(!0);const{apiFetch:oe}=await Y(async()=>{const{apiFetch:ce}=await import("./api-CyvozDRd.js");return{apiFetch:ce}},[]),_e=await oe("/api/admin/me/update",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(N)}),ve=await _e.json().catch(()=>null);if(!_e.ok){const ce=ve?.error||ve?.message||"Unable to update credentials";throw new Error(ce)}t({title:"Credentials updated",description:"Your admin profile has been updated."}),F(S||te),await C()}catch(oe){console.error(oe),t({title:"Update failed",description:oe?.message||"Unable to update credentials.",variant:"destructive"})}finally{V(!1)}},R=async()=>{d(!1);try{G(!0),t({title:"Data cleanup started",description:"This may take a few moments. Check the audit logs for results."});const{apiFetch:A}=await Y(async()=>{const{apiFetch:N}=await import("./api-CyvozDRd.js");return{apiFetch:N}},[]),te=await A("/api/admin/data-cleanup",{method:"POST",headers:{"Content-Type":"application/json"}}),S=await te.json().catch(()=>null);if(!te.ok){const N=S?.error||S?.message||"Cleanup failed";throw new Error(N)}t({title:"Cleanup job started",description:S?.message||"Data cleanup is running in the background."}),setTimeout(()=>{C()},2e3)}catch(A){console.error(A),t({title:"Cleanup failed",description:A?.message||"Unable to trigger cleanup.",variant:"destructive"})}finally{G(!1)}},M=A=>e.jsxs("div",{className:"rounded-lg border bg-card/40 p-3 shadow-sm",children:[e.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-2 text-xs text-foreground
2/70",children:[e.jsx("span",{children:ka(A.created_at)}),A.role&&e.jsx("span",{className:"rounded-full bg-muted px-2 py-0.5 text-[11px] uppercase tracking-wide text-foreground/80",children:A.role})]}),e.jsx("div",{className:"mt-1 text-sm font-semibold text-foreground",children:A.displayName}),A.targetDisplayName&&e.jsxs("div",{className:"text-xs text-foreground/70",children:["Target:"," ",e.jsx("span",{className:"font-medium text-foreground",children:A.targetDisplayName})]}),e.jsx("div",{className:"mt-2 text-sm font-medium text-primary",children:A.action}),e.jsx(_a,{meta:A.meta})]},A.id);return e.jsxs("div",{className:"space-y-6",children:[e.jsx("div",{className:"rounded-lg border border-orange-200 bg-orange-50/50 dark:border-orange-900/50 dark:bg-orange-950/20 p-4 shadow-sm",children:e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsx(Ks,{className:"h-5 w-5 text-orange-600 dark:text-orange-400 mt-0.5"}),e.jsxs("div",{className:"flex-1",children:[e.jsx("h3",{className:"text-lg font-semibold text-foreground mb-1",children:"Database Cleanup & Optimization"}),e.jsx("p",{className:"text-sm text-foreground/70 mb-4",children:"Free tier optimization: Automatically removes data older than 3 months. Manual cleanup runs immediately and shows detailed statistics."}),e.jsxs("div",{className:"rounded-md bg-background/60 p-3 mb-4 border",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-2",children:[e.jsx(lt,{className:"h-4 w-4 text-blue-600 dark:text-blue-400"}),e.jsx("span",{className:"text-sm font-medium text-foreground",children:"Automatic Schedule"})]}),e.jsxs("ul",{className:"text-xs text-foreground/70 space-y-1 ml-6",children:[e.jsx("li",{children:"⢠Runs every 24 hours automatically"}),e.jsx("li",{children:"⢠First run: 5 minutes after server starts"}),e.jsx("li",{children:"⢠Removes: Messages, Posts, Comments, Notifications, Audit Logs"}),e.jsx("li",{children:"⢠Retention: 3 months for most data, 1 month for read notifications"})]})]}),W&&e.jsxs("div",{className:"rounded-md bg-green-50 dark:bg-green-950/30 border border-green-200 dark:border-green-900/50 p-3 mb-4",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-2",children:[e.jsx(Ws,{className:"h-4 w-4 text-green-600 dark:text-green-400"}),e.jsx("span",{className:"text-sm font-medium text-green-900 dark:text-green-100",children:"Last Cleanup Results"})]}),e.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-4 gap-2 text-xs",children:[e.jsxs("div",{className:"bg-background/60 rounded p-2",children:[e.jsx("div",{className:"text-foreground/60",children:"Messages"}),e.jsx("div",{className:"text-lg font-semibold text-foreground",children:W.messages.deleted})]}),e.jsxs("div",{className:"bg-background/60 rounded p-2",children:[e.jsx("div",{className:"text-foreground/60",children:"Posts"}),e.jsx("div",{className:"text-lg font-semibold text-foreground",children:W.posts.deleted})]}),e.jsxs("div",{className:"bg-background/60 rounded p-2",children:[e.jsx("div",{className:"text-foreground/60",children:"Media Files"}),e.jsx("div",{className:"text-lg font-semibold text-foreground",children:W.posts.mediaDeleted})]}),e.jsxs("div",{className:"bg-background/60 rounded p-2",children:[e.jsx("div",{className:"text-foreground/60",children:"Notifications"}),e.jsx("div",{className:"text-lg font-semibold text-foreground",children:W.notifications.deleted})]})]})]}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"text-sm text-foreground/70",children:[e.jsx("strong",{className:"text-foreground",children:"Manual cleanup"})," removes all old data immediately. Check server logs for detailed progress."]}),e.jsxs(w,{onClick:()=>d(!0),disabled:L,variant:"destructive",size:"sm",className:"ml-4",children:[e.jsx(Na,{className:"h-4 w-4 mr-2"}),L?"Running...":"Run Cleanup Now"]})]})]})]})}),E&&e.jsx("div",{className:"fixed inset-0 bg-black/50 flex items-center justify-center z-50 p-4",children:e.jsxs("div",{className:"bg-background rounded-lg shadow-xl max-w-md w-full p-6",children:[e.jsxs("div",{className:"flex items-start gap-3 mb-4",children:[e.jsx(Ns,{className:"h-6 w-6 text-orange-600 dar
2k:text-orange-400 flex-shrink-0 mt-0.5"}),e.jsxs("div",{children:[e.jsx("h3",{className:"text-lg font-semibold text-foreground mb-2",children:"Confirm Data Cleanup"}),e.jsx("p",{className:"text-sm text-foreground/70 mb-3",children:"This will permanently delete:"}),e.jsxs("ul",{className:"text-sm text-foreground/70 space-y-1 mb-4",children:[e.jsx("li",{children:"⢠Messages older than 3 months (unless saved)"}),e.jsx("li",{children:"⢠Posts older than 3 months + their media files"}),e.jsx("li",{children:"⢠Comments older than 3 months"}),e.jsx("li",{children:"⢠Audit logs older than 3 months"}),e.jsx("li",{children:"⢠Old notifications (read: 1 month, unread: 3 months)"}),e.jsx("li",{children:"⢠Orphaned media files (unreferenced for 1 week)"})]}),e.jsx("p",{className:"text-sm font-medium text-orange-600 dark:text-orange-400",children:"This action cannot be undone!"})]})]}),e.jsxs("div",{className:"flex gap-3 justify-end",children:[e.jsx(w,{variant:"outline",onClick:()=>d(!1),children:"Cancel"}),e.jsx(w,{variant:"destructive",onClick:R,children:"Yes, Clean Up Data"})]})]})}),e.jsxs("div",{className:"space-y-3",children:[e.jsx("h3",{className:"text-lg font-semibold text-foreground",children:"Recent Activity"}),e.jsxs("div",{className:"grid gap-4 md:grid-cols-2",children:[e.jsxs("div",{children:[e.jsx("h4",{className:"mb-2 font-semibold text-sm",children:"User actions"}),e.jsxs("div",{className:"space-y-2 rounded-lg border p-3",children:[b.length===0&&e.jsx("div",{className:"text-sm text-foreground/70",children:"No user actions recorded yet."}),e.jsx("div",{className:"max-h-[60vh] space-y-2 overflow-auto pr-1",children:b.map(M)})]})]}),e.jsxs("div",{children:[e.jsx("h4",{className:"mb-2 font-semibold text-sm",children:"Admin / Teacher actions"}),e.jsxs("div",{className:"space-y-2 rounded-lg border p-3",children:[k.length===0&&e.jsx("div",{className:"text-sm text-foreground/70",children:"No admin or teacher events recorded yet."}),e.jsx("div",{className:"max-h-[60vh] space-y-2 overflow-auto pr-1",children:k.map(M)})]})]})]})]}),e.jsxs("div",{className:"rounded-lg border p-4 shadow-sm",children:[e.jsx("div",{className:"flex flex-col gap-2 sm:flex-row sm:items-baseline sm:justify-between",children:e.jsxs("div",{children:[e.jsx("h3",{className:"text-lg font-semibold",children:"Update admin credentials"}),e.jsx("p",{className:"text-sm text-foreground/70",children:"Change your username or password. You must confirm changes with your current password."})]})}),e.jsxs("form",{onSubmit:T,className:"mt-4 grid gap-3 md:grid-cols-2",children:[e.jsxs("div",{className:"md:col-span-2",children:[e.jsx("label",{htmlFor:"identifier",className:"mb-1 block text-sm font-medium text-foreground",children:"Username or email"}),e.jsx("input",{id:"identifier",name:"identifier",className:"h-10 w-full rounded-md border px-3",value:n,onChange:A=>i(A.target.value),autoComplete:"username",required:!0})]}),e.jsxs("div",{className:"md:col-span-2",children:[e.jsx("label",{htmlFor:"currentPassword",className:"mb-1 block text-sm font-medium text-foreground",children:"Current password"}),e.jsx("input",{id:"currentPassword",name:"currentPassword",type:"password",className:"h-10 w-full rounded-md border px-3",value:l,onChange:A=>c(A.target.value),autoComplete:"current-password",required:!0})]}),e.jsxs("div",{children:[e.jsx("label",{htmlFor:"newUsername",className:"mb-1 block text-sm font-medium text-foreground",children:"New username (optional)"}),e.jsx("input",{id:"newUsername",name:"newUsername",className:"h-10 w-full rounded-md border px-3",value:u,onChange:A=>x(A.target.value),autoComplete:"off"})]}),e.jsxs("div",{children:[e.jsx("label",{htmlFor:"newPassword",className:"mb-1 block text-sm font-medium text-foreground",children:"New password (optional)"}),e.jsx("input",{id:"newPassword",name:"newPassword",type:"password",className:"h-10 w-full rounded-md border px-3",value:p,onChange:A=>v(A.target.value),autoComplete:"new-password"})]}),e.jsxs("div",{className:"md:col-span-2",children:[e.jsx("label",{htmlFor:"confirmPassword",className:"mb-1 block text-sm font-medium text-foreground",children:"Confirm new password"}),e.jsx("input",{id:"confirmPassword",name:"confirmPassword",type:"password",className:"h-10 w-full rounded-md border px-3",value:y,onChange:A=>I(A.target.value),autoComplete:"new-password"})]}),e.jsxs("div",{className:"md:col-span-2 flex flex-col gap-2 sm:flex-row sm:justify-end",children:[e.jsx(w,{type:"button",variant:"outline",onClick:()=>F(),className:"w-full sm:w-auto",children:"Clear"}),e.jsx(w,{type:"submit",className:"w-full sm:w-auto",disabled:U,children:U?"Saving changes...":"Save changes"})]})]})]})]})}function Sa(){const{user:a}=xs(),{toast:t}=Pe(),[s,r]=m.useState(!1),[n,i]=m.useState(null),[l,c]=m.useState(!1),[u,x]=m.useState(null),[p,v]=m.useState(1),[y,I]=m.useState(0),U=m.useRef(null),V=m.useRef(null),[L,G]=m.useState({name:"",email:"",ph
2one:"",profile_picture_url:""});m.useEffect(()=>{W()},[]);const W=async()=>{try{r(!0);const k=await we("/api/admin/me");k&&(G({name:k.name||"",email:k.email||"",phone:k.phone||"",profile_picture_url:k.profile_picture_url||""}),k.profile_picture_url&&i(k.profile_picture_url))}catch(k){console.error("Failed to load admin profile:",k),a&&G({name:a.name||"",email:a.email||"",phone:"",profile_picture_url:""})}finally{r(!1)}},ne=async k=>{const b=k.target.files?.[0];if(!b)return;if(!b.type.startsWith("image/")){t({title:"Invalid File",description:"Please select an image file (JPG, PNG, etc.)",variant:"destructive"});return}const F=10*1024*1024;if(b.size>F){t({title:"File Too Large",description:"Image must be less than 10MB",variant:"destructive"});return}const T=new FileReader;T.onload=R=>{x(R.target?.result),v(1),I(0),c(!0)},T.onerror=()=>{t({title:"Error",description:"Failed to read image file",variant:"destructive"})},T.readAsDataURL(b)},E=async()=>new Promise((k,b)=>{const F=U.current,T=V.current;if(!F||!T){b(new Error("Canvas not ready"));return}const R=F.getContext("2d");if(!R){b(new Error("Canvas context not available"));return}const M=300;F.width=M,F.height=M,R.clearRect(0,0,M,M);const A=p,te=T.naturalWidth*A,S=T.naturalHeight*A;R.save(),R.translate(M/2,M/2),R.rotate(y*Math.PI/180),R.drawImage(T,-te/2,-S/2,te,S),R.restore();const N=F.toDataURL("image/jpeg",.85).split(",")[1];k(N)}),d=async()=>{try{r(!0);const k=await E(),b=await we("/api/admin/upload-admin-profile-picture",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({data:k})});i(b.url),G(F=>({...F,profile_picture_url:b.url})),c(!1),x(null),t({title:"Success",description:"Profile picture updated successfully"})}catch(k){t({title:"Error",description:k?.message||"Failed to upload profile picture",variant:"destructive"})}finally{r(!1)}},C=async()=>{try{if(r(!0),L.email&&L.email!==a?.email&&!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(L.email)){t({title:"Invalid Email",description:"Please enter a valid email address",variant:"destructive"}),r(!1);return}const k={name:L.name,email:L.email,phone:L.phone,profile_picture_url:L.profile_picture_url};await we("/api/admin/me",{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify(k)})&&(t({title:"Success",description:"Profile updated successfully"+(L.email!==a?.email?". Please log in again with your new email.":"")}),L.email!==a?.email?setTimeout(()=>{window.location.href="/"},2e3):setTimeout(()=>window.location.reload(),500))}catch(k){console.error("Update error:",k),t({title:"Error",description:k?.message||"Failed to update profile",variant:"destructive"})}finally{r(!1)}};return e.jsxs(e.Fragment,{children:[l&&u&&e.jsx("div",{className:"fixed inset-0 z-50 bg-black/80 flex items-center justify-center p-4",children:e.jsxs(Fs,{className:"w-full max-w-2xl p-6 space-y-4",children:[e.jsxs("div",{className:"flex justify-between items-center",children:[e.jsx("h3",{className:"text-xl font-semibold",children:"Adjust Your Profile Picture"}),e.jsx("button",{onClick:()=>{c(!1),x(null)},className:"text-foreground/50 hover:text-foreground",children:e.jsx(Me,{size:24})})]}),e.jsxs("div",{className:"relative bg-muted rounded-lg p-4 flex items-center justify-center",children:[e.jsx("div",{className:"relative w-[300px] h-[300px] rounded-full overflow-hidden border-4 border-primary",children:e.jsx("div",{className:"absolute inset-0",style:{transform:`scale(${p}) rotate(${y}deg)`,transition:"transform 0.1s ease-out"},children:e.jsx("img",{ref:V,src:u,alt:"Preview",className:"w-full h-full object-cover"})})}),e.jsx("canvas",{ref:U,className:"hidden"})]}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{children:[e.jsxs("label",{className:"text-sm font-medium mb-2 block flex items-center gap-2",children:[e.jsx(Rs,{size:16}),"Zoom: ",p.toFixed(1),"x"]}),e.jsx("input",{type:"range",min:"0.5",max:"3",step:"0.1",value:p,onChange:k=>v(parseFloat(k.target.value)),className:"w-full"})]}),e.jsxs("div",{children:[e.jsxs("label",{className:"text-sm font-medium mb-2 block flex items-center gap-2",children:[e.jsx(Is,{size:16}),"Rotation: ",y,"°"]}),e.jsx("input",{type:"range",min:"0",max:"360",step:"15",value:y,onChange:k=>I(parseInt(k.target.value)),className:"w-full"})]})]}),e.jsxs("div",{className:"flex gap-3",children:[e.jsx(w,{onClick:d,disabled:s,className:"flex-1",children:s?"Uploading...":"Upload Picture"}),e.jsx(w,{onClick:()=>{c(!1),x(null)},variant:"outline",disabled:s,children:"Cancel"})]})]})}),e.jsxs("div",{className:"space-y-4 max-w-2xl",children:[e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-medium mb-2",children:"Profile Picture"}),e.jsxs("div",{className:"flex items-center gap-4",children:[n?e.jsx("img",{src:n,alt:"Profile",className:"w-24 h-24 rounded-full object-cover border"}):e.jsx("div",{className:"w-24 h-24 rounded-full bg-muted flex items-center justify-center text-3xl",children:"ð¤"}),e.jsxs("div",{children:[e.jsx("input",{type:"file",accept:"image/*",onChange:ne,disabled:s,id:"adminProfilePicture",className:"hidden"}),e.jsx("label",{htmlFor:"adminProfilePicture",className:"inline-block px-4 py-2 rounded-md border cursor-pointer hover:bg-muted disabled:opacity-50",children:s?"Uploading...":"Change Picture"})]})]})]}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-medium mb-2",children:"Full Name"}),e.jsx("input",{type:"text",value:L.name,onChange:k=>G({...L,name:k.target.value}),className:"w-full px-3 py-2 rounded-md border bg-background",placeholder:"Your full name"})]}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-medium mb-2",children:"Email Address"}),e.jsx("input",{type:"email",value:L.email,onChange:k=>G({...L,email:k.target.value}),className:"w-full px-3 py-2 rounded-md border bg-background",placeholder:"[email protected]"}),L.email!==a?.email&&e.jsx("p",{className:"text-xs text-amber-600 dar
2k:text-amber-500 mt-1 font-medium",children:"â ï¸ Changing your email will require you to log in again with the new email address. Make sure you have access to this email for password recovery."}),e.jsx("p",{className:"text-xs text-muted-foreground mt-1",children:"This email is used for login and password recovery."})]}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-medium mb-2",children:"Phone Number"}),e.jsx("input",{type:"tel",value:L.phone,onChange:k=>G({...L,phone:k.target.value}),className:"w-full px-3 py-2 rounded-md border bg-background",placeholder:"Your phone number"})]}),e.jsx(w,{onClick:C,disabled:s,className:"w-full",children:s?"Saving...":"Save Profile"})]})]})}const Pt=["Teacher illness or emergency","Student requested cancellation","Schedule conflict","Facility unavailable","Weather-related cancellation","Holiday observance","Professional development/training","Family emergency"];function Ta(){const[a,t]=m.useState("schedule"),[s,r]=m.useState(""),[n,i]=m.useState({}),[l,c]=m.useState(!1),[u,x]=m.useState({calendarEmbedLink:"",workingHours:{}}),[p,v]=m.useState([]),[y,I]=m.useState([]),[U,V]=m.useState([]),[L,G]=m.useState([]),[W,ne]=m.useState({}),[E,d]=m.useState(!1),[C,k]=m.useState(null),[b,F]=m.useState(!1),[T,R]=m.useState([]),[M,A]=m.useState([]),[te,S]=m.useState(""),[N,oe]=m.useState({studentId:"",slotId:"",lessonType:"solo",instrument:"",selectedDate:"",recurrence:"none",recurrenceEndDate:""}),[_e,ve]=m.useState(!1),[le,ce]=m.useState(null),[pe,Ne]=m.useState("prewritten"),[be,ye]=m.useState(Pt[0]),[Ce,xe]=m.useState(""),[he,$]=m.useState(""),{toast:Q}=Pe();m.useEffect(()=>{f(),_(),re()},[]);const f=async()=>{try{const h=await we("/api/admin/schedule/settings");r(h.calendarEmbedLink||""),i(h.workingHours||{}),x({calendarEmbedLink:h.calendarEmbedLink||"",workingHours:h.workingHours||{}})}catch(h){console.error("Failed to load schedule:",h)}},_=async()=>{try{d(!0);const h=await we("/api/admin/trial-requests");v(h.trials||[])}catch(h){console.error("Failed to load trial requests:",h)}finally{d(!1)}},re=async()=>{try{const q=(await we("/api/admin/lessons")).lessons||[];I(q);const X=new Date,me=new Date(X.getFullYear(),X.getMonth(),X.getDate()),o=new Date(me);o.setDate(o.getDate()+1);const g=new Date(o);g.setDate(g.getDate()+1);const z=q.filter(ie=>{const de=new Date(ie.date);return de>=me&&de<o}),Z=q.filter(ie=>{const de=new Date(ie.date);return de>=o&&de<g}),K=q.filter(ie=>new Date(ie.date)>=me),ee={};K.forEach(ie=>{const de=ie.studentId||`${ie.studentName}|${ie.studentEmail}`;ee[de]||(ee[de]=[]),ee[de].push(ie)}),Object.keys(ee).forEach(ie=>{ee[ie].sort((de,He)=>{const mt=new Date(`${de.date}T${de.startTime}`).getTime(),ht=new Date(`${He.date}T${He.startTime}`).getTime();return mt-ht})}),V(z),G(Z),ne(ee)}catch(h){console.error("Failed to load lessons:",h)}},je=async()=>{try{const h=await we("/api/admin/students");R(Array.isArray(h)?h:[])}catch(h){console.error("Failed to load students:",h)}},Fe=async h=>{try{const q=await we(`/api/admin/available-slots?date=${h}`);A(q.slots||[])}catch(q){console.error("Failed to load available slots:",q)}},qe=async()=>{F(!0),S(""),await je()},st=async()=>{if(!N.studentId||!N.slotId||!N.instrument){Q({title:"Missing Information",description:"Please fill in all required fields",variant:"destructive"});return}try{d(!0);const h=await we("/api/admin/bookings",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({studentId:N.studentId,slotId:N.slotId,lessonType:N.lessonType,instrument:N.instrument,recurrence:N.recurrence,recurrenceEndDate:N.recurrenceEndDate})}),q=h.bookingsCreated>1?`Created ${h.bookingsCreated} recurring bookings${h.bookingsSkipped>0?` (${h.bookingsSkipped} dates skipped - slots unavailable)`:""}`:"Lesson booking created successfully";Q({title:"Success",description:q}),F(!1),oe({studentId:"",slotId:"",lessonType:"solo",instrument:"",selectedDate:"",recurrence:"none",recurrenceEndDate:""}),await re()}catch(h){console.error("Failed to create booking:",h),Q({title:"Error",description:"Failed to create booking",variant:"destructive"})}finally{d(!1)}},Be=async()=>{const h=pe==="prewritten"?be:Ce;if(!le||!h.trim()){Q({title:"Missing Information",description:"Please provide a reason for cancellation",variant:"destructive"});return}
2try{d(!0),await we(`/api/admin/bookings/${le.id}`,{method:"DELETE",headers:{"Content-Type":"application/json"},body:JSON.stringify({reason:h})}),await re(),Q({title:"Success",description:"Booking cancelled and student notified"}),ve(!1),ce(null),xe(""),Ne("prewritten"),ye(Pt[0])}catch(q){console.error("Failed to cancel booking:",q),Q({title:"Error",description:"Failed to cancel booking",variant:"destructive"})}finally{d(!1)}},at=async()=>{try{d(!0),(await we("/api/admin/schedule/settings",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(u)})).ok?(r(u.calendarEmbedLink),i(u.workingHours),c(!1),Q({title:"Success",description:"Schedule settings saved successfully"})):Q({title:"Error",description:"Failed to save schedule settings",variant:"destructive"})}catch(h){console.error("Error saving schedule:",h),Q({title:"Error",description:"Failed to save schedule settings",variant:"destructive"})}finally{d(!1)}},kt=async h=>{k(h),$("")},_t=async()=>{if(C)try{d(!0),(await we(`/api/admin/trial-requests/${C.id}/approve`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({notes:he,assignedTime:C.preferredTime,assignedDate:C.preferredDate})})).ok?(Q({title:"Success",description:"Trial lesson approved and student notified"}),k(null),$(""),await _()):Q({title:"Error",description:"Failed to approve trial lesson",variant:"destructive"})}catch(h){console.error("Error approving trial:",h),Q({title:"Error",description:"Failed to approve trial lesson",variant:"destructive"})}finally{d(!1)}},Ct=async h=>{if(confirm("Are you sure you want to reject this trial request?"))try{(await we(`/api/admin/trial-requests/${h}/reject`,{method:"POST"})).ok?(Q({title:"Success",description:"Trial request rejected"}),await _()):Q({title:"Error",description:"Failed to reject trial request",variant:"destructive"})}catch(q){console.error("Error rejecting trial:",q),Q({title:"Error",description:"Failed to reject trial request",variant:"destructive"})}},rt=["monday","tuesday","wednesday","thursday","friday","saturday","sunday"],Le=p.filter(h=>h.status==="pending");return e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"flex gap-2 border-b",children:[e.jsx("button",{onClick:()=>t("schedule"),className:`px-4 py-2 font-medium transition-colors ${a==="schedule"?"border-b-2 border-primary text-primary":"text-foreground/60 hover:text-foreground"}`,children:"ð
My Schedule"}),e.jsx("button",{onClick:()=>t("lessons"),className:`px-4 py-2 font-medium transition-colors ${a==="lessons"?"border-b-2 border-primary text-primary":"text-foreground/60 hover:text-foreground"}`,children:"ð My Lessons"}),e.jsxs("button",{onClick:()=>t("trials"),className:`px-4 py-2 font-medium transition-colors relative ${a==="trials"?"border-b-2 border-primary text-primary":"text-foreground/60 hover:text-foreground"}`,children:["ð¯ Trial Requests",Le.length>0&&e.jsx("span",{className:"absolute -top-1 -right-1 bg-destructive text-destructive-foreground text-xs rounded-full w-5 h-5 flex items-center justify-center",children:Le.length})]})]}),a==="schedule"&&e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("h3",{className:"text-xl font-semibold",children:"My Schedule & Availability"}),!l&&e.jsx(w,{onClick:()=>c(!0),children:"Edit Schedule"})]}),l?e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-medium mb-2",children:"Calendar Embed Link"}),e.jsx("input",{type:"url",className:"w-full px-3 py-2 border rounded-md",placeholder:"e.g., https://calendar.google.com/calendar/embed?src=...",value:u.calendarEmbedLink,onChange:h=>x({...u,calendarEmbedLink:h.target.value})}),e.jsx("p",{className:"text-xs text-foreground/60 mt-1",children:"Paste your Google Calendar embed URL or any calendar iframe source"})]}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-medium mb-2",children:"Working Hours"}),e.jsx("p",{className:"text-xs text-foreground/60 mb-3",children:"Set your availability for each day of the week. These slots will be available for trial bookings."}),e.jsx("div",{className:"space-y-3",children:rt.map(h=>e.jsxs("div",{className:"border rounded-md p-3",children:[e.jsxs("div",{className:"flex items-center justify-between mb-2",children:[e.jsx("label",{className:"font-medium capitalize",children:h}),e.jsx(w,{variant:"outline",size:"sm",onClick:()=>{const q=u.workingHours[h]||[];x({...u,workingHours:{...u.workingHours,[h]:[...q,{start:"09:00",end:"17:00"}]}})},children:"+ Add Time Slot"})]}),(u.workingHours[h]||[]).map((q,X)=>e.jsxs("div",{className:"flex items-center gap-2 mt-2",children:[e.jsx("input",{type:"time",className:"px-2 py-1 border rounded text-sm",value:q.start,onCh
2ange:me=>{const o=[...u.workingHours[h]||[]];o[X]={...o[X],start:me.target.value},x({...u,workingHours:{...u.workingHours,[h]:o}})}}),e.jsx("span",{children:"to"}),e.jsx("input",{type:"time",className:"px-2 py-1 border rounded text-sm",value:q.end,onChange:me=>{const o=[...u.workingHours[h]||[]];o[X]={...o[X],end:me.target.value},x({...u,workingHours:{...u.workingHours,[h]:o}})}}),e.jsx(w,{variant:"outline",size:"sm",onClick:()=>{const me=(u.workingHours[h]||[]).filter((o,g)=>g!==X);x({...u,workingHours:{...u.workingHours,[h]:me}})},children:"Remove"})]},X))]},h))})]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(w,{onClick:at,disabled:E,children:E?"Saving...":"Save Changes"}),e.jsx(w,{variant:"outline",onClick:()=>{c(!1),x({calendarEmbedLink:s,workingHours:n})},children:"Cancel"})]})]}):e.jsxs("div",{className:"space-y-6",children:[s?e.jsx("div",{className:"border rounded-md overflow-hidden",children:e.jsx("iframe",{src:s,className:"w-full h-[600px] border-0",title:"Admin Calendar"})}):e.jsxs("div",{className:"border border-dashed rounded-md p-8 text-center text-foreground/60",children:[e.jsx("p",{className:"mb-2",children:"No calendar configured"}),e.jsx("p",{className:"text-sm",children:'Click "Edit Schedule" to add your calendar embed link'})]}),e.jsxs("div",{children:[e.jsx("h3",{className:"text-lg font-semibold mb-3",children:"Working Hours"}),Object.keys(n).length===0?e.jsx("p",{className:"text-foreground/60 text-sm",children:'No working hours set. Click "Edit Schedule" to configure your availability.'}):e.jsx("div",{className:"grid gap-2",children:rt.map(h=>{const q=n[h]||[];return e.jsxs("div",{className:"flex items-center gap-3 border-b pb-2",children:[e.jsx("span",{className:"w-24 font-medium capitalize",children:h}),e.jsx("span",{className:"text-foreground/70",children:q.length===0?"Unavailable":q.map((X,me)=>e.jsxs("span",{children:[X.start," - ",X.end,me<q.length-1&&", "]},me))})]},h)})})]})]})]}),a==="lessons"&&e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"flex justify-between items-center",children:[e.jsx("h3",{className:"text-xl font-semibold",children:"Scheduled Lessons"}),e.jsxs(w,{onClick:qe,className:"gap-2",children:[e.jsx(fa,{className:"w-4 h-4"}),"Add Booking"]})]}),e.jsxs("div",{className:"border rounded-lg",children:[e.jsx("div",{className:"bg-muted px-4 py-3 border-b",children:e.jsxs("h4",{className:"font-semibold flex items-center gap-2",children:[e.jsx(xt,{className:"w-5 h-5"}),"Today's Lessons"]})}),U.length===0?e.jsx("div",{className:"text-center py-6 text-foreground/60",children:e.jsx("p",{className:"text-sm",children:"No lessons scheduled for today"})}):e.jsx("div",{className:"max-h-[300px] overflow-y-auto p-4 space-y-3",children:U.map(h=>e.jsx("div",{className:"border rounded-lg p-4 hover:bg-accent/5 transition-colors",children:e.jsxs("div",{className:"flex items-start justify-between",children:[e.jsxs("div",{className:"flex-1",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-2",children:[e.jsx("h4",{className:"font-semibold text-lg",children:h.instrument}),h.lessonType==="trial"&&e.jsx("span",{className:"px-2 py-1 text-xs rounded-full bg-green-100 text-green-800",children:"Trial Lesson"}),h.lessonType==="solo"&&e.jsx("span",{className:"px-2 py-1 text-xs rounded-full bg-blue-100 text-blue-800",children:"Solo"}),h.lessonType==="band"&&e.jsx("span",{className:"px-2 py-1 text-xs rounded-full bg-purple-100 text-purple-800",children:"Band"}),h.lessonType==="extended"&&e.jsx("span",{className:"px-2 py-1 text-xs rounded-full bg-orange-100 text-orange-800",children:"Extended (1hr)"})]}),e.jsxs("p",{className:"text-sm text-foreground/70 flex items-center gap-1",children:[e.jsx(We,{className:"w-4 h-4"}),h.studentName]}),h.studentEmail&&e.jsxs("p",{className:"text-sm text-foreground/60 flex items-center gap-1",children:[e.jsx(ft,{className:"w-4 h-4"}),h.studentEmail]}),e.jsx("div",{className:"flex items-center gap-4 mt-2 text-sm",children:e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(lt,{className:"w-4 h-4"}),h.startTime," - ",h.endTime]})})]}),e.jsxs(w,{variant:"destructive",size:"sm",onClick:()=>{ce(h),ve(!0)},children:[e.jsx(Me,{className:"w-4 h-4 mr-1"}),"Cancel"]})]})},h.id))})]}),e.jsxs("div",{className:"border rounded-lg",children:[e.jsx("div",{className:"bg-muted px-4 py-3 border-b",children:e.jsxs("h4",{className:"font-semibold flex items-center gap-2",children:[e.jsx(xt,{className:"w-5 h-5"}),"Tomorrow's Lessons"]})}),L.length===0?e.jsx("div",{className:"text-center py-6 text-foreground
2/60",children:e.jsx("p",{className:"text-sm",children:"No lessons scheduled for tomorrow"})}):e.jsx("div",{className:"max-h-[300px] overflow-y-auto p-4 space-y-3",children:L.map(h=>e.jsx("div",{className:"border rounded-lg p-4 hover:bg-accent/5 transition-colors",children:e.jsxs("div",{className:"flex items-start justify-between",children:[e.jsxs("div",{className:"flex-1",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-2",children:[e.jsx("h4",{className:"font-semibold text-lg",children:h.instrument}),h.lessonType==="trial"&&e.jsx("span",{className:"px-2 py-1 text-xs rounded-full bg-green-100 text-green-800",children:"Trial Lesson"}),h.lessonType==="solo"&&e.jsx("span",{className:"px-2 py-1 text-xs rounded-full bg-blue-100 text-blue-800",children:"Solo"}),h.lessonType==="band"&&e.jsx("span",{className:"px-2 py-1 text-xs rounded-full bg-purple-100 text-purple-800",children:"Band"}),h.lessonType==="extended"&&e.jsx("span",{className:"px-2 py-1 text-xs rounded-full bg-orange-100 text-orange-800",children:"Extended (1hr)"})]}),e.jsxs("p",{className:"text-sm text-foreground/70 flex items-center gap-1",children:[e.jsx(We,{className:"w-4 h-4"}),h.studentName]}),h.studentEmail&&e.jsxs("p",{className:"text-sm text-foreground/60 flex items-center gap-1",children:[e.jsx(ft,{className:"w-4 h-4"}),h.studentEmail]}),e.jsx("div",{className:"flex items-center gap-4 mt-2 text-sm",children:e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(lt,{className:"w-4 h-4"}),h.startTime," - ",h.endTime]})})]}),e.jsxs(w,{variant:"destructive",size:"sm",onClick:()=>{ce(h),ve(!0)},children:[e.jsx(Me,{className:"w-4 h-4 mr-1"}),"Cancel"]})]})},h.id))})]}),e.jsxs("div",{className:"border rounded-lg",children:[e.jsx("div",{className:"bg-muted px-4 py-3 border-b",children:e.jsxs("h4",{className:"font-semibold flex items-center gap-2",children:[e.jsx(We,{className:"w-5 h-5"}),"Students & Their Upcoming Lessons"]})}),Object.keys(W).length===0?e.jsx("div",{className:"text-center py-6 text-foreground/60",children:e.jsx("p",{className:"text-sm",children:"No students with scheduled lessons"})}):e.jsx("div",{className:"max-h-[500px] overflow-y-auto p-4 space-y-4",children:Object.entries(W).sort(([h,q],[X,me])=>{const o=q[0]?.studentName||"",g=me[0]?.studentName||"";return o.localeCompare(g)}).map(([h,q])=>{const X=q[0]?.studentName||"Unknown",me=q[0]?.studentEmail||"";return e.jsxs("div",{className:"border rounded-lg p-4 bg-accent/5",children:[e.jsxs("div",{className:"mb-3 pb-3 border-b",children:[e.jsxs("h5",{className:"font-semibold text-base flex items-center gap-2",children:[e.jsx(We,{className:"w-4 h-4"}),X]}),me&&e.jsxs("p",{className:"text-sm text-foreground/60 mt-1 flex items-center gap-1 ml-6",children:[e.jsx(ft,{className:"w-3 h-3"}),me]}),e.jsxs("p",{className:"text-xs text-foreground/50 mt-1 ml-6",children:[q.length," lesson",q.length!==1?"s":""," scheduled"]})]}),e.jsx("div",{className:"space-y-2",children:q.map((o,g)=>{const Z=new Date(o.date).toLocaleDateString("en-US",{weekday:"short",month:"short",day:"numeric",year:"numeric"});return e.jsxs("div",{className:"flex items-center justify-between p-3 bg-background rounded border hover:border-primary/50 transition-colors",children:[e.jsxs("div",{className:"flex-1",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-1",children:[e.jsx("span",{className:"font-medium text-sm",children:o.instrument}),o.lessonType==="trial"&&e.jsx("span",{className:"px-2 py-0.5 text-xs rounded-full bg-green-100 text-green-800",children:"Trial"}),o.lessonType==="solo"&&e.jsx("span",{className:"px-2 py-0.5 text-xs rounded-full bg-blue-100 text-blue-800",children:"Solo"}),o.lessonType==="band"&&e.jsx("span",{className:"px-2 py-0.5 text-xs rounded-full bg-purple-100 text-purple-800",children:"Band"}),o.lessonType==="extended"&&e.jsx("span",{className:"px-2 py-0.5 text-xs rounded-full bg-orange-100 text-orange-800",children:"1hr"})]}),e.jsxs("div",{className:"flex items-center gap-3 text-xs text-foreground/70",children:[e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(xt,{className:"w-3 h-3"}),Z]}),e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(lt,{className:"w-3 h-3"}),o.startTime," - ",o.endTime]})]})]}),e.jsx(w,{variant:"ghost",size:"sm",className:"text-destructive hover:text-destructive hover:bg-destructive/10",onClick:()=>{ce(o),ve(!0)},children:e.jsx(Me,{className:"w-4 h-4"})})]},`${o.id}-${g}`)})})]},h)})})]})]}),a==="trials"&&e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex justify-between items-center",children:[e.jsx("h3",{className:"text-xl font-semibold",children:"Trial Lesson Requests"}
2),e.jsxs("div",{className:"text-sm text-foreground/70",children:[Le.length," pending request",Le.length!==1?"s":""]})]}),E?e.jsx("div",{className:"text-center py-8 text-foreground/60",children:"Loading trial requests..."}):Le.length===0?e.jsx("div",{className:"text-center py-8 text-foreground/60",children:"No pending trial requests"}):e.jsx("div",{className:"grid gap-4",children:Le.map(h=>e.jsx("div",{className:"border rounded-lg p-6 bg-card",children:e.jsxs("div",{className:"flex items-start justify-between mb-4",children:[e.jsxs("div",{className:"flex-1",children:[e.jsxs("div",{className:"flex items-center gap-3 mb-3",children:[e.jsxs("h4",{className:"text-lg font-semibold",children:[h.firstName," ",h.lastName]}),e.jsx("span",{className:"px-3 py-1 text-xs bg-yellow-100 text-yellow-800 rounded-full",children:"Pending"})]}),e.jsxs("div",{className:"grid md:grid-cols-2 gap-3 text-sm mb-4",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(ft,{className:"w-4 h-4 text-foreground/60"}),h.email]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Ls,{className:"w-4 h-4 text-foreground/60"}),h.phone]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(We,{className:"w-4 h-4 text-foreground/60"}),"Age: ",new Date().getFullYear()-new Date(h.dateOfBirth).getFullYear()]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Ds,{className:"w-4 h-4 text-foreground/60"}),h.instruments.join(", ")]})]}),e.jsxs("div",{className:"bg-muted/50 rounded-md p-3 mb-3",children:[e.jsx("div",{className:"text-sm font-medium mb-1",children:"Requested Schedule:"}),e.jsxs("div",{className:"flex items-center gap-4 text-sm text-foreground/70",children:[e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(xt,{className:"w-4 h-4"}),new Date(h.preferredDate).toLocaleDateString()]}),e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(lt,{className:"w-4 h-4"}),h.preferredTime]})]})]}),h.notes&&e.jsxs("div",{className:"text-sm",children:[e.jsx("strong",{children:"Notes:"})," ",h.notes]}),e.jsxs("div",{className:"text-xs text-foreground/50 mt-2",children:["Submitted ",new Date(h.createdAt).toLocaleDateString()]})]}),e.jsxs("div",{className:"flex flex-col gap-2 ml-4",children:[e.jsxs(w,{size:"sm",onClick:()=>kt(h),className:"bg-green-600 hover:bg-green-700",children:[e.jsx(fs,{className:"w-4 h-4 mr-1"}),"Accept"]}),e.jsxs(w,{size:"sm",variant:"destructive",onClick:()=>Ct(h.id),children:[e.jsx(Me,{className:"w-4 h-4 mr-1"}),"Reject"]})]})]})},h.id))})]}),C&&e.jsx("div",{className:"fixed inset-0 bg-black/50 flex items-center justify-center z-50",children:e.jsxs("div",{className:"bg-card rounded-lg p-6 max-w-md w-full mx-4",children:[e.jsx("h3",{className:"text-lg font-semibold mb-4",children:"Approve Trial Lesson"}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{children:[e.jsxs("p",{className:"text-sm font-medium mb-2",children:["Student: ",C.firstName," ",C.lastName]}),e.jsxs("p",{className:"text-sm text-foreground/70",children:["Instruments: ",C.instruments.join(", ")]}),e.jsxs("p",{className:"text-sm text-foreground/70",children:["Requested: ",new Date(C.preferredDate).toLocaleDateString()," at ",C.preferredTime]})]}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-medium mb-2",children:"Notes (optional)"}),e.jsx("textarea",{className:"w-full px-3 py-2 border rounded-md",rows:3,placeholder:"Add any notes for the student...",value:he,onChange:h=>$(h.target.value)})]}),e.jsxs("div",{className:"flex gap-2 justify-end",children:[e.jsx(w,{variant:"outline",onClick:()=>k(null),disabled:E,children:"Cancel"}),e.jsx(w,{onClick:_t,disabled:E,className:"bg-green-600 hover:bg-green-700",children:E?"Approving...":"Approve & Notify"})]})]})]})}),b&&e.jsx("div",{className:"fixed inset-0 bg-black/50 flex items-center justify-center z-50",children:e.jsxs("div",{className:"bg-card rounded-lg p-6 max-w-lg w-full mx-4 max-h-[90vh] overflow-y-auto",children:[e.jsxs("div",{className:"flex justify-between items-center mb-4",children:[e.jsx("h3",{className:"text-lg font-semibold",children:"Create Lesson Booking"}),e.jsx("button",{onClick:()=>
2F(!1),className:"text-foreground/60 hover:text-foreground",children:e.jsx(Me,{className:"w-5 h-5"})})]}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{children:[e.jsxs("label",{className:"block text-sm font-medium mb-2",children:["Student ",e.jsx("span",{className:"text-red-500",children:"*"})]}),e.jsx("input",{type:"text",className:"w-full px-3 py-2 border rounded-md mb-2",placeholder:"Search students by name or email...",value:te,onChange:h=>S(h.target.value)}),e.jsxs("select",{className:"w-full px-3 py-2 border rounded-md",value:N.studentId,onChange:h=>{const q=T.find(X=>X.id===h.target.value);oe({...N,studentId:h.target.value,instrument:q?.instruments?.[0]||N.instrument})},size:6,children:[e.jsx("option",{value:"",children:"Select a student..."}),T.filter(h=>te===""||h.name.toLowerCase().includes(te.toLowerCase())||h.email.toLowerCase().includes(te.toLowerCase())).map(h=>e.jsxs("option",{value:h.id,children:[h.name," (",h.email,")"]},h.id))]})]}),e.jsxs("div",{children:[e.jsxs("label",{className:"block text-sm font-medium mb-2",children:["Lesson Type ",e.jsx("span",{className:"text-red-500",children:"*"})]}),e.jsxs("select",{className:"w-full px-3 py-2 border rounded-md",value:N.lessonType,onChange:h=>oe({...N,lessonType:h.target.value}),children:[e.jsx("option",{value:"solo",children:"Solo (30 min)"}),e.jsx("option",{value:"band",children:"Band (30 min)"}),e.jsx("option",{value:"extended",children:"Extended (60 min)"})]})]}),e.jsxs("div",{children:[e.jsxs("label",{className:"block text-sm font-medium mb-2",children:["Instrument ",e.jsx("span",{className:"text-red-500",children:"*"})]}),(()=>{const q=T.find(X=>X.id===N.studentId)?.instruments||[];return q.length===0?e.jsx("div",{className:"w-full px-3 py-2 border rounded-md bg-muted text-muted-foreground",children:N.studentId?"No instruments on file for this student":"Please select a student first"}):e.jsxs("select",{className:"w-full px-3 py-2 border rounded-md",value:N.instrument,onChange:X=>oe({...N,instrument:X.target.value}),children:[e.jsx("option",{value:"",children:"Select an instrument..."}),q.map(X=>e.jsx("option",{value:X,children:X},X))]})})()]}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-medium mb-2",children:"Recurrence"}),e.jsxs("select",{className:"w-full px-3 py-2 border rounded-md",value:N.recurrence,onChange:h=>oe({...N,recurrence:h.target.value}),children:[e.jsx("option",{value:"none",children:"One-time lesson"}),e.jsx("option",{value:"weekly",children:"Weekly (same day/time)"}),e.jsx("option",{value:"biweekly",children:"Biweekly (every 2 weeks)"}),e.jsx("option",{value:"monthly",children:"Monthly (same day/time)"})]})]}),N.recurrence!=="none"&&e.jsxs("div",{children:[e.jsxs("label",{className:"block text-sm font-medium mb-2",children:["End Date ",e.jsx("span",{className:"text-red-500",children:"*"})]}),e.jsx("input",{type:"date",className:"w-full px-3 py-2 border rounded-md",value:N.recurrenceEndDate,onChange:h=>oe({...N,recurrenceEndDate:h.target.value}),min:N.selectedDate||new Date().toISOString().split("T")[0]}),e.jsxs("p",{className:"text-xs text-foreground/60 mt-1",children:["Lessons will repeat ",N.recurrence==="weekly"?"every week":N.recurrence==="biweekly"?"every 2 weeks":"every month"," until this date"]})]}),e.jsxs("div",{children:[e.jsxs("label",{className:"block text-sm font-medium mb-2",children:["Date ",e.jsx("span",{className:"text-red-500",children:"*"})]}),e.jsx("input",{type:"date",className:"w-full px-3 py-2 border rounded-md",value:N.selectedDate,onChange:h=>{oe({...N,selectedDate:h.target.value,slotId:""}),Fe(h.target.value)},min:new Date().toISOString().split("T")[0]})]}),N.selectedDate&&e.jsxs("div",{children:[e.jsxs("label",{className:"block text-sm font-medium mb-2",children:["Available Time Slots ",e.jsx("span",{className:"text-red-500",children:"*"})]}),M.length===0?e.jsx("p",{className:"text-sm text-foreground/60 py-4",children:"No available slots for this date. Try another date."}):e.jsxs("select",{className:"w-full px-3 py-2 border rounded-md",value:N.slotId,onChange:h=>oe({...N,slotId:h.target.value}),children:[e.jsx("option",{value:"",children:"Select a time slot..."}),M.map(h=>e.jsxs("option",{value:h.id,children:[h.slotTime," (",h.durationMinutes," min)"]},h.id))]})]}),e.jsxs("div",{className:"flex gap-2 justify-end pt-4 border-t",children:[e.jsx(w,{variant:"outline",onClick:()=>F(!1),disabled:E,children:"Cancel"}),e.jsx(w,{onClick:st,disabled:E||!N.studentId||!N.slotId||!N.instrument||N.recurrence!=="none"&&!N.recurrenceEndDate,children:E?"Creating...":N.recurrence!=="none"?"Create Recurring Bookings":"Create Booking"})]})]})]})}),_e&&le&&e.jsx("div",{className:"fixed inset-0 bg-black/50 flex items-center justify-center z-50 p-4",children:e.jsxs("div",{className:"bg-card rounded-lg p-6 max-w-md w-full max-h-[90vh] overflow-y-auto",children:[e.jsx("h3",{className:"text-lg font-semibold mb-4",children:"Cancel Booking"}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"bg-muted p-4 rounded-lg",children:[e.jsx("p",{className:"font-medium",children:le.instrument}
2),e.jsxs("p",{className:"text-sm text-foreground/70",children:[new Date(le.date).toLocaleDateString()," at ",le.startTime]}),e.jsxs("p",{className:"text-sm text-foreground/70",children:["Student: ",le.studentName]}),le.lessonType!=="trial"&&e.jsxs("p",{className:"text-sm text-foreground/70 capitalize",children:["Type: ",le.lessonType]})]}),e.jsxs("div",{className:"space-y-3",children:[e.jsx(Ge,{className:"text-base font-semibold",children:"Cancellation Reason"}),e.jsxs(Bt,{value:pe,onValueChange:h=>Ne(h),children:[e.jsxs("div",{className:"flex items-center space-x-3",children:[e.jsx(At,{value:"prewritten",id:"reason-prewritten"}),e.jsx(Ge,{htmlFor:"reason-prewritten",className:"cursor-pointer",children:"Select from common reasons"})]}),e.jsxs("div",{className:"flex items-center space-x-3",children:[e.jsx(At,{value:"custom",id:"reason-custom"}),e.jsx(Ge,{htmlFor:"reason-custom",className:"cursor-pointer",children:"Write custom reason"})]})]})]}),pe==="prewritten"&&e.jsxs("div",{className:"space-y-2",children:[e.jsx(Ge,{children:"Select Reason"}),e.jsx(Bt,{value:be,onValueChange:ye,children:Pt.map(h=>e.jsxs("div",{className:"flex items-center space-x-3 p-2",children:[e.jsx(At,{value:h,id:`reason-${h}`}),e.jsx(Ge,{htmlFor:`reason-${h}`,className:"cursor-pointer font-normal",children:h})]},h))})]}),pe==="custom"&&e.jsxs("div",{children:[e.jsxs(Ge,{htmlFor:"custom-reason",children:["Custom Reason ",e.jsx("span",{className:"text-red-500",children:"*"})]}),e.jsx("textarea",{id:"custom-reason",className:"w-full px-3 py-2 border rounded-md mt-2",rows:4,placeholder:"Provide a reason for the cancellation (will be sent to student)...",value:Ce,onChange:h=>xe(h.target.value)})]}),e.jsxs("div",{className:"bg-destructive/10 border border-destructive/20 p-3 rounded-lg",children:[e.jsx("p",{className:"text-sm text-destructive font-medium",children:"â ï¸ This action cannot be undone"}),e.jsx("p",{className:"text-sm text-foreground/70 mt-1",children:"The student will be notified via email and the slot will become available again."})]}),e.jsxs("div",{className:"flex gap-2 justify-end",children:[e.jsx(w,{variant:"outline",onClick:()=>{ve(!1),ce(null),xe("")},disabled:E,children:"Keep Booking"}),e.jsx(w,{variant:"destructive",onClick:Be,disabled:E||pe==="custom"&&!Ce.trim(),children:E?"Cancelling...":"Cancel Booking"})]})]})]})})]})}function Ea({onClose:a}){const[t,s]=m.useState(""),[r,n]=m.useState(""),[i,l]=m.useState([]),[c,u]=m.useState(""),[x,p]=m.useState([]),[v,y]=m.useState(null),{toast:I}=Pe(),[U,V]=m.useState(!1),L=E=>{const d=E.target.files;d&&l(Array.from(d))},G=async()=>{if(c)try{const E=await As(c,9);p(E)}catch(E){console.error(E),I({title:"Error",description:"Unable to search images"})}},W=E=>{y(E)},ne=async()=>{if(!t||!r){I({title:"Missing fields",description:"Subject and content are required"});return}V(!0);try{const E=new FormData;E.append("subject",t),E.append("html",r),v&&E.append("unsplash_image",v.full||v.thumb),i.forEach((k,b)=>E.append("attachments",k,k.name));const{apiFetch:d}=await Y(async()=>{const{apiFetch:k}=await import("./api-CyvozDRd.js");return{apiFetch:k}},[]);if(!(await d("/api/admin/newsletters",{method:"POST",body:E})).ok)throw new Error("Failed to send newsletter");I({title:"Sent",description:"Newsletter queued/sent"}),s(""),n(""),l([]),y(null),p([]),a?.()}catch(E){console.error(E),I({title:"Error",description:E?.message||"Unable to send"})}finally{V(!1)}};return e.jsxs("div",{className:"bg-card rounded-md p-4 max-w-3xl w-full",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("h3",{className:"text-lg font-semibold",children:"Compose newsletter"}),e.jsx("div",{className:"text-sm text-foreground/70",children:"Use the editor to craft a magazine-style email"})]}),e.jsxs("div",{className:"mt-3 grid gap-2",children:[e.jsx("input",{value:t,onChange:E=>s(E.target.value),placeholder:"Subject",className:"h-10 rounded-md border px-3"}),e.jsxs("div",{className:"grid gap-2",children:[e.jsxs("div",{className:"flex gap-2",children:[e.jsx("input",{value:c,onChange:E=>u(E.target.value),placeholder:"Search for header image (Unsplash)",className:"h-10 rounded-md border px-3 flex-1"}),e.jsx(w,{onClick:G,variant:"outline",children:"Search"})]}),v?e.jsxs("div",{className:"p-2 border rounded-md",children:[e.jsx("div",{className:"mb-2 text-sm text-foreground
2/70",children:"Selected image (Unsplash)"}),e.jsx("img",{src:v.full||v.thumb,alt:v.alt||"",className:"w-full h-48 object-cover rounded"}),e.jsx("div",{className:"flex gap-2 mt-2",children:e.jsx(w,{variant:"ghost",onClick:()=>y(null),children:"Remove"})})]}):x.length>0&&e.jsx("div",{className:"grid grid-cols-3 gap-2",children:x.map(E=>e.jsx("button",{onClick:()=>W(E),className:"rounded overflow-hidden border",children:e.jsx("img",{src:E.thumb,alt:E.alt||"",className:"w-full h-24 object-cover"})},E.id))})]}),e.jsx("textarea",{value:r,onChange:E=>n(E.target.value),placeholder:"HTML content (you can paste HTML)",className:"rounded-md border px-3 py-2 min-h-[160px]"}),e.jsx("input",{type:"file",multiple:!0,onChange:L}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(w,{onClick:ne,variant:"gradient",size:"lg",children:"Send newsletter"}),e.jsx(w,{onClick:()=>{s(""),n(""),l([]),y(null),p([])},variant:"outline",children:"Clear"}),e.jsx(w,{onClick:()=>a?.(),variant:"ghost",children:"Close"})]}),i.length>0&&e.jsxs("div",{className:"mt-2 text-sm text-foreground/70",children:["Attachments: ",i.map(E=>E.name).join(", ")]})]})]})}function Aa(){const[a,t]=m.useState([]),[s,r]=m.useState(!0),[n,i]=m.useState(!1),[l,c]=m.useState(null),{toast:u}=Pe(),x=m.useRef(null),p=m.useRef(null),v=m.useRef(null),y=m.useRef(null),I=m.useRef(null);m.useEffect(()=>{U()},[]);async function U(){try{r(!0);const{apiFetch:d}=await Y(async()=>{const{apiFetch:k}=await import("./api-CyvozDRd.js");return{apiFetch:k}},[]);console.log("[ForumMgmt] Loading forums from /api/forums...");const C=await d("/api/forums");if(console.log("[ForumMgmt] Forums loaded:",C),C&&C.ok)t(C.forums||[]);else throw new Error(C?.error||"No forums returned from server")}catch(d){const C=d?.message||String(d)||"Failed to load forums";console.error("[ForumMgmt] Error loading forums:",{message:C,error:d}),u({title:"Error loading forums",description:C,variant:"destructive"})}finally{r(!1)}}function V(){x.current&&(x.current.value=""),p.current&&(p.current.value=""),v.current&&(v.current.value=""),y.current&&(y.current.value=""),I.current&&(I.current.value="")}async function L(){const d=x.current?.value?.trim(),C=p.current?.value?.trim(),k=v.current?.value?.trim(),b=y.current?.value?.trim()||null,F=I.current?.value?.trim()||null;if(!d||!C){u({title:"Validation Error",description:"Name and slug are required",variant:"destructive"});return}if(!/^[a-z0-9-]+$/.test(C)){u({title:"Invalid slug",description:"Slug must contain only lowercase letters, numbers, and hyphens",variant:"destructive"});return}try{const{apiFetch:T}=await Y(async()=>{const{apiFetch:A}=await import("./api-CyvozDRd.js");return{apiFetch:A}},[]);let R;const M={name:d,slug:C,description:k||null,icon:b,color:F};if(console.log("ð¤ Forum API Request:",{method:l?"PATCH":"POST",url:l?`/api/forums/${l}`:"/api/forums",payload:M}),l?R=await T(`/api/forums/${l}`,{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify({name:d,description:k||null,icon:b,color:F})}):R=await T("/api/forums",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(M)}),console.log("ð¥ Forum API Response:",R),console.log("[ForumMgmt] API Response:",{ok:R?.ok,hasError:!!R?.error,forum:R?.forum}),R&&R.ok)u({title:"Success â
",description:l?"Forum updated successfully":"Forum created successfully"}),i(!1),c(null),V(),await U();else{const A=R?.error||"Failed to save forum";console.error("[ForumMgmt] API returned non-ok response:",{error:A,response:R}),u({title:"Server Error",description:A,variant:"destructive"})}}catch(T){const R=T?.message||String(T)||"Failed to save forum";console.error("[ForumMgmt] Forum API Error:",{message:R,errorType:T?.constructor?.name,statusCode:T?.statusCode,status:T?.status,originalError:T});let M=R;R.includes("403")?M="Permission denied. You must be an admin to create forums.":R.includes("409")?M="A forum with this name or slug already exists.":R.includes("400")?M="Invalid input. Please check all required fields.":R.includes("Failed to fetch")&&(M="Network error. Please check your connection and try again."),u({title:"Error â",description:M,variant:"destructive"})}}async function G(d,C){const k=["general","announcements","assignments","resources"],b=a.find(F=>F.id===d);if(b&&k.includes(b.slug)){console.warn("[ForumMgmt] Attempt to delete default forum:",C),u({title:"Cannot Delete",description:"Default forums cannot be deleted",variant:"destructive"});return}if(!window.confirm(`Are you sure you want to delete "${C}"?`)){console.log("[ForumMgmt] Delete cancelled by user");return}try{const{apiFetch:F}=await Y(async()=>{const{apiFetch:R}=await import("./api-CyvozDRd.js");return{apiFetch:R}},[]);console.log("[ForumMgmt] Deleting forum:",d);const T=await F(`/api/forums/${d}`,{method:"DELETE"});if(T&&T.ok)console.log("[ForumMgmt] Forum deleted successfully:",d),u({title:"Success â
",description:"Forum deleted successfully"}),await U();else throw new Error(T?.error||"Failed to delete forum")}catch(F){const T=F?.message||String(F)||"Failed to delete forum";console.error("[ForumMgmt] Error deleting forum:",{forumId:d,message:T,error:F}),u({title:"Error â",description:T,variant:"destructive"})}}function W(d){console.log("[ForumMgmt] Editing forum:",d.name),c(d.id),x.current&&(x.current.value=d.name),p.current&&(p.current.value=d.slug),v.current&&(v.current.value=d.description||""),y.current&&(y.current.value=d.icon||""),I.current&&(I.current.value=d.color||""),i(!0)}function ne(){console.log("[ForumMgmt] Cancelled editing"),i(!1),c(null),V()}const E=["general","announcements","assignments","resources"];return e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{children:[e.jsx("h3",{className:"text-lg font-semibold mb-2",children:"Forum Management"}
2),e.jsx("p",{className:"text-sm text-foreground/70 mb-4",children:"Create and manage forums that are accessible to all students. Use forums to organize discussions by topic."})]}),s?e.jsx("div",{className:"text-center py-8 text-foreground/60",children:"Loading forums..."}):e.jsxs(e.Fragment,{children:[!n&&e.jsx(w,{onClick:()=>i(!0),className:"rounded-lg",children:"â Create Forum"}),n&&e.jsxs("div",{className:"rounded-lg border bg-card p-4 space-y-4",children:[e.jsx("h4",{className:"font-semibold",children:l?"Edit Forum":"Create New Forum"}),e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-medium mb-1",children:"Forum Name *"}),e.jsx("input",{ref:x,type:"text",placeholder:"e.g., General Discussion",className:"w-full rounded-lg border px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-primary/50"})]}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-medium mb-1",children:"Slug (URL-safe) *"}),e.jsx("input",{ref:p,type:"text",placeholder:"e.g., general-discussion",disabled:!!l,className:"w-full rounded-lg border px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-primary/50 disabled:bg-muted",title:"Can only be set on creation"}),e.jsx("p",{className:"text-xs text-foreground/60 mt-1",children:"Lowercase letters, numbers, and hyphens only"})]}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-medium mb-1",children:"Description"}),e.jsx("textarea",{ref:v,placeholder:"Brief description of this forum...",className:"w-full rounded-lg border px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-primary/50 resize-none min-h-[80px]"})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-medium mb-2",children:"Icon (emoji)"}),e.jsx("div",{className:"flex gap-2 flex-wrap",children:["ð¬","ð","ð","ð¢","ðµ","ð¸","ð¹","ð¥","ð","ð","â","ð¡"].map(d=>e.jsx("button",{type:"button",onClick:()=>{y.current&&(y.current.value=d)},className:`text-2xl p-2 rounded-lg border-2 transition-all hover:scale-110 ${y.current?.value===d?"border-primary bg-primary/10":"border-transparent hover:border-muted"}`,children:d},d))}),e.jsx("input",{ref:y,type:"text",placeholder:"or paste emoji here",maxLength:2,className:"w-full mt-2 rounded-lg border px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-primary/50"})]}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-medium mb-2",children:"Color"}),e.jsxs("div",{className:"flex gap-2 items-center",children:[e.jsx("input",{ref:I,type:"color",defaultValue:"#3b82f6",className:"h-12 w-20 rounded-lg border cursor-pointer"}),e.jsx("div",{className:"flex-1",children:e.jsx("input",{type:"text",value:I.current?.value||"#3b82f6",onChange:d=>{I.current&&(I.current.value=d.target.value)},placeholder:"#3b82f6",className:"w-full rounded-lg border px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-primary/50 font-mono"})})]})]})]})]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(w,{onClick:L,className:"rounded-lg",children:l?"Update Forum":"Create Forum"}),e.jsx(w,{variant:"outline",onClick:ne,className:"rounded-lg",children:"Cancel"})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs("h4",{className:"font-semibold text-sm",children:["Forums (",a.length,")"]}),e.jsx("div",{className:"grid gap-2",children:a.map(d=>{const C=E.includes(d.slug);return e.jsxs("div",{className:"rounded-lg border bg-card p-3 flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-3 flex-1",children:[d.icon&&e.jsx("span",{className:"text-xl",children:d.icon}),e.jsxs("div",{className:"flex-1",children:[e.jsxs("div",{className:"font-medium",children:[d.name,C&&e.jsx("span",{className:"ml-2 text-xs bg-blue-100 text-blue-800 px-2 py-0.5 rounded dark:bg-blue-900 dark:text-blue-200",children:"Default"})]}),e.jsx("p",{className:"text-xs text-foreground/60",children:d.slug}),d.description&&e.jsx("p",{className:"text-xs text-foreground/70 mt-1",children:d.description})]})]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(w,{size:"sm",variant:"outline",onClick:()=>W(d),className:"rounded-lg text-xs",children:"Edit"}),!C&&e.jsx(w,{size:"sm",variant:"destructive",onClick:()=>G(d.id,d.name),className:"rounded-lg text-xs",children:"Delete"})]})]},d.id)})})]})]})]})}function Pa(){const[a,t]=m.useState([]),[s,r]=m.useState(!0),[n,i]=m.useState(null),[l,c]=m.useState(!1),[u,x]=m.useState(null),[p,v]=m.useState(""),[y,I]=m.useState(""),[U,V]=m.useState(!1),{toast:L}=Pe(),G=async()=>{try{r(!0);const{apiFetch:d}=await Y(async()=>{const{apiFetch:b}=await import("./api-CyvozDRd.js");return{apiFetch:b}},[]),C=await d("/api/admin/students"),k=Array.isArray(C)?C.filter(b=>b.intake_status==="pending"):[];t(k)}catch(d){console.error("Failed to load students:",d),t([])}finally{r(!1)}};m.useEffect(()=>{G()},[]);const W=(d,C)=>{i(d),x(C),v(""),I(""),c(!0)},ne=async()=>
2{if(!(!n||!u)){V(!0);try{const{apiFetch:d}=await Y(async()=>{const{apiFetch:C}=await import("./api-CyvozDRd.js");return{apiFetch:C}},[]);if(u==="approve")await d(`/api/admin/students/${n.student_id}/approve`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({notes:p})}),L({title:"Success",description:"Student approved and notified"});else{if(!y.trim()){L({title:"Error",description:"Rejection reason is required",variant:"destructive"}),V(!1);return}await d(`/api/admin/students/${n.student_id}/reject`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({reason:y,notes:p})}),L({title:"Success",description:"Student rejected and notified"})}c(!1),i(null),x(null),await G()}catch(d){console.error("Failed to process review:",d),L({title:"Error",description:d?.message||"Failed to process review",variant:"destructive"})}finally{V(!1)}}},E=async d=>{if(confirm("Are you sure you want to reset this student's status to pending?"))try{const{apiFetch:C}=await Y(async()=>{const{apiFetch:k}=await import("./api-CyvozDRd.js");return{apiFetch:k}},[]);await C(`/api/admin/students/${d}/reset`,{method:"POST"}),L({title:"Success",description:"Student status reset to pending"}),await G()}catch(C){console.error("Failed to reset student:",C),L({title:"Error",description:C?.message||"Failed to reset student",variant:"destructive"})}};return s?e.jsx("div",{className:"text-sm text-foreground/70",children:"Loading pending applications..."}):e.jsxs("div",{className:"space-y-4",children:[e.jsx("div",{className:"flex justify-between items-center",children:e.jsxs("div",{className:"text-sm text-foreground/70",children:[a.length," pending application",a.length!==1?"s":""]})}),a.length===0?e.jsx("div",{className:"text-center py-8 text-foreground/60",children:"No pending applications. All applications have been reviewed."}):e.jsx("div",{className:"grid gap-4",children:a.map(d=>e.jsxs("div",{className:"border rounded-lg p-6",children:[e.jsxs("div",{className:"flex items-start justify-between",children:[e.jsxs("div",{className:"flex-1",children:[e.jsxs("div",{className:"flex items-center gap-4 mb-3",children:[e.jsx("h3",{className:"text-lg font-semibold",children:d.name}),e.jsx("span",{className:"px-3 py-1 text-xs bg-yellow-100 text-yellow-800 rounded-full",children:"Pending Review"})]}),e.jsxs("div",{className:"grid md:grid-cols-2 gap-4 text-sm",children:[e.jsxs("div",{children:[e.jsx("strong",{children:"Email:"})," ",d.email]}),e.jsxs("div",{children:[e.jsx("strong",{children:"Phone:"})," ",d.phone]}),e.jsxs("div",{children:[e.jsx("strong",{children:"Age:"})," ",d.age]}),e.jsxs("div",{children:[e.jsx("strong",{children:"Instruments:"})," ",d.instruments?.join(", ")||"Not specified"]}),d.parent_name&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{children:[e.jsx("strong",{children:"Parent:"})," ",d.parent_name]}),e.jsxs("div",{children:[e.jsx("strong",{children:"Parent Email:"})," ",d.parent_email]})]})]}),d.goals&&e.jsxs("div",{className:"mt-3",children:[e.jsx("strong",{children:"Goals:"})," ",d.goals]}),d.experience&&e.jsxs("div",{className:"mt-2",children:[e.jsx("strong",{children:"Experience:"})," ",d.experience]}),e.jsxs("div",{className:"mt-2 text-xs text-foreground/50",children:["Submitted ",new Date(d.intake_submitted_at).toLocaleDateString()]})]}),e.jsxs("div",{className:"flex flex-col gap-2 ml-4",children:[e.jsx(w,{size:"sm",onClick:()=>W(d,"approve"),className:"bg-green-600 hover:bg-green-700",children:"Approve"}),e.jsx(w,{size:"sm",variant:"destructive",onClick:()=>W(d,"reject"),children:"Reject"}),e.jsx(w,{size:"sm",variant:"outline",onClick:()=>E(d.student_id),children:"Reset"})]})]}),e.jsxs("details",{className:"mt-4",children:[e.jsx("summary",{className:"cursor-pointer text-sm font-medium text-primary hover:text-primary/80",children:"View full application details"}),e.jsxs("div",{className:"mt-3 space-y-3 text-sm",children:[d.address&&e.jsxs("div",{children:[e.jsx("strong",{children:"Address:"})," ",d.address]}),d.availability&&e.jsxs("div",{children:[e.jsx("strong",{children:"Availability:"})," ",d.availability]}),d.additional_info&&e.jsxs("div",{children:[e.jsx("strong",{children:"Additional Info:"})," ",d.additional_info]}),d.allergies&&e.jsxs("div",{children:[e.jsx("strong",{children:"Allergies:"})," ",d.allergies]}),d.medications&&e.jsxs("div",{children:[e.jsx("strong",{children:"Medications:"})," ",d.medications]}),d.emergency_contacts&&e.jsxs("div",{children:[e.jsx("strong",{children:"Emergency Contacts:"})," ",d.emergency_contacts]})]})]})]},d.id))}),l&&n&&e.jsx("div",{className:"fixed inset-0 z-50 flex items-center justify-center bg-black/50 p-4",children:e.jsxs("div",{className:"w-full max-w-md rounded-lg bg-card p-6 shadow-xl",children:[e.jsxs("h3",{className:"text-lg font-semibold mb-4",children:[u==="approve"?"Approve":"Reject"," Application"]}
2),e.jsxs("p",{className:"text-sm text-foreground/70 mb-4",children:[n.name," - ",n.email]}),u==="reject"&&e.jsxs("div",{className:"mb-4",children:[e.jsxs("label",{className:"block text-sm font-medium mb-2",children:["Rejection Reason ",e.jsx("span",{className:"text-red-500",children:"*"})]}),e.jsxs("select",{value:y,onChange:d=>I(d.target.value),className:"w-full h-10 rounded-md border px-3 mb-2",children:[e.jsx("option",{value:"",children:"Select a reason"}),e.jsx("option",{value:"Not suitable for our teaching style",children:"Not suitable for our teaching style"}),e.jsx("option",{value:"Insufficient information provided",children:"Insufficient information provided"}),e.jsx("option",{value:"Age requirements not met",children:"Age requirements not met"}),e.jsx("option",{value:"Location not in service area",children:"Location not in service area"}),e.jsx("option",{value:"Currently at capacity",children:"Currently at capacity"}),e.jsx("option",{value:"Other",children:"Other (specify in notes)"})]})]}),e.jsxs("div",{className:"mb-4",children:[e.jsx("label",{className:"block text-sm font-medium mb-2",children:"Review Notes (optional)"}),e.jsx("textarea",{value:p,onChange:d=>v(d.target.value),className:"w-full rounded-md border px-3 py-2",rows:3,placeholder:"Add any notes about this decision..."})]}),e.jsxs("div",{className:"flex gap-2 justify-end",children:[e.jsx(w,{variant:"outline",onClick:()=>c(!1),disabled:U,children:"Cancel"}),e.jsx(w,{onClick:ne,disabled:U||u==="reject"&&!y.trim(),className:u==="approve"?"bg-green-600 hover:bg-green-700":"",children:U?"Processing...":u==="approve"?"Approve":"Reject"})]})]})})]})}const gt=[{platform:"facebook",name:"Facebook",icon:"Facebook",placeholder:"https://facebook.com/yourpage",color:"bg-[#1877F2]"},{platform:"twitter",name:"Twitter / X",icon:"Twitter",placeholder:"https://twitter.com/yourhandle",color:"bg-[#1DA1F2]"},{platform:"instagram",name:"Instagram",icon:"Instagram",placeholder:"https://instagram.com/yourprofile",color:"bg-gradient-to-br from-[#833AB4] via-[#FD1D1D] to-[#F77737]"},{platform:"tiktok",name:"TikTok",icon:"Music2",placeholder:"https://tiktok.com/@yourhandle",color:"bg-black"},{platform:"whatsapp",name:"WhatsApp",icon:"MessageCircle",placeholder:"https://wa.me/447764501732",color:"bg-[#25D366]"},{platform:"youtube",name:"YouTube",icon:"Youtube",placeholder:"https://youtube.com/@yourchannel",color:"bg-[#FF0000]"},{platform:"linkedin",name:"LinkedIn",icon:"Linkedin",placeholder:"https://linkedin.com/company/yourcompany",color:"bg-[#0A66C2]"}],Gt=a=>({Facebook:Zt,Twitter:Ts,Instagram:Ss,Linkedin:Cs,Youtube:_s,MessageCircle:ks,Music2:ws})[a]||Zt;function Fa(){const[a,t]=m.useState([]),[s,r]=m.useState(!1),{toast:n}=Pe();m.useEffect(()=>{i()},[]);const i=()=>{try{const p=localStorage.getItem("inTuneSocialMedia");if(p)t(JSON.parse(p));else{const v=gt.map(y=>({platform:y.platform,name:y.name,url:"",visible:!1,icon:y.icon}));t(v)}}catch(p){console.error("Error loading social links:",p),n({title:"Error",description:"Failed to load social media links",variant:"destructive"})}},l=async()=>{r(!0);try{console.log("Saving social links:",a);const p=a.filter(v=>v.visible&&v.url);console.log("Visible links to save:",p),localStorage.setItem("inTuneSocialMedia",JSON.stringify(a)),window.dispatchEvent(new CustomEvent("socialMediaUpdated",{detail:a})),n({title:"Saved",description:`Social media links saved successfully. ${p.length} visible.`})}catch(p){console.error("Error saving social links:",p),n({title:"Error",description:"Failed to save social media links",variant:"destructive"})}finally{r(!1)}},c=(p,v)=>{t(y=>y.map(I=>I.platform===p?{...I,url:v}:I))},u=p=>{t(v=>v.map(y=>y.platform===p?{...y,visible:!y.visible}:y))},x=()=>{if(!confirm("Are you sure you want to reset all social media links? This will clear all URLs and hide all platforms."))return;const p=gt.map(v=>({platform:v.platform,name:v.name,url:"",visible:!1,icon:v.icon}));t(p),localStorage.setItem("inTuneSocialMedia",JSON.stringify(p)),n({title:"Reset",description:"All social media links have been reset"})};return e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx("h2",{className:"text-xl font-semibold",children:"Social Media Links"}
2),e.jsx("p",{className:"text-sm text-foreground/70 mt-1",children:"Manage social media links displayed in the footer. Toggle visibility to show/hide on the website."})]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(w,{onClick:x,variant:"outline",size:"sm",children:"Reset All"}),e.jsx(w,{onClick:l,variant:"gradient",disabled:s,children:s?"Saving...":"Save Changes"})]})]}),e.jsx("div",{className:"grid gap-4",children:gt.map(p=>{const v=a.find(I=>I.platform===p.platform),y=Gt(p.icon);return e.jsx("div",{className:"border rounded-lg p-4 hover:shadow-md transition-shadow",children:e.jsxs("div",{className:"flex items-start gap-4",children:[e.jsx("div",{className:`w-12 h-12 rounded-lg ${p.color} flex items-center justify-center flex-shrink-0`,children:e.jsx(y,{className:"w-6 h-6 text-white"})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"flex items-center justify-between mb-2",children:[e.jsx("h3",{className:"font-semibold",children:p.name}),e.jsxs("div",{className:"flex items-center gap-2",children:[v?.url&&e.jsx("a",{href:v.url,target:"_blank",rel:"noopener noreferrer",className:"text-primary hover:text-primary/80",title:"Preview link",children:e.jsx(ea,{size:16})}),e.jsx(w,{onClick:()=>u(p.platform),variant:v?.visible?"default":"outline",size:"sm",className:"min-w-[100px]",children:v?.visible?e.jsxs(e.Fragment,{children:[e.jsx(fs,{size:14,className:"mr-1"}),"Visible"]}):e.jsxs(e.Fragment,{children:[e.jsx(Me,{size:14,className:"mr-1"}),"Hidden"]})})]})]}),e.jsx("input",{type:"url",value:v?.url||"",onChange:I=>c(p.platform,I.target.value),placeholder:p.placeholder,className:"w-full h-10 rounded-md border bg-background px-3 text-sm outline-none focus-visible:ring-2 focus-visible:ring-ring"}),v?.visible&&!v?.url&&e.jsx("p",{className:"text-xs text-amber-600 dark:text-amber-400 mt-1",children:"â ï¸ This platform is set to visible but has no URL"})]})]})},p.platform)})}),e.jsxs("div",{className:"border rounded-lg p-6 bg-muted/30",children:[e.jsx("h3",{className:"font-semibold mb-3",children:"Footer Preview"}),e.jsx("p",{className:"text-sm text-foreground/70 mb-4",children:"This is how your social media icons will appear in the footer (circular design):"}),e.jsxs("div",{className:"bg-background rounded-lg p-4 border",children:[e.jsx("p",{className:"text-xs font-semibold mb-3 text-foreground/60 uppercase tracking-wider",children:"Connect With Us"}),e.jsxs("div",{className:"flex flex-wrap gap-2",children:[a.filter(p=>p.visible&&p.url).map(p=>{const v=gt.find(I=>I.platform===p.platform),y=Gt(p.icon);return e.jsx("div",{className:`w-10 h-10 rounded-full ${v?.color} flex items-center justify-center text-white shadow-md hover:shadow-lg hover:scale-110 transform transition-all cursor-pointer`,title:p.name,children:e.jsx(y,{size:18})},p.platform)}),a.filter(p=>p.visible&&p.url).length===0&&e.jsx("p",{className:"text-sm text-foreground/50 italic",children:"No social media links are currently visible. Add URLs and toggle visibility above."})]})]})]}),e.jsxs("div",{className:"grid grid-cols-3 gap-4",children:[e.jsxs("div",{className:"border rounded-lg p-4 text-center",children:[e.jsx("div",{className:"text-2xl font-bold text-primary",children:a.length}),e.jsx("div",{className:"text-sm text-foreground/70 mt-1",children:"Total Platforms"})]}),e.jsxs("div",{className:"border rounded-lg p-4 text-center",children:[e.jsx("div",{className:"text-2xl font-bold text-green-600",children:a.filter(p=>p.visible).length}),e.jsx("div",{className:"text-sm text-foreground/70 mt-1",children:"Visible"})]}),e.jsxs("div",{className:"border rounded-lg p-4 text-center",children:[e.jsx("div",{className:"text-2xl font-bold text-amber-600",children:a.filter(p=>p.url&&!p.visible).length}),e.jsx("div",{className:"text-sm text-foreground/70 mt-1",children:"Hidden (with URL)"})]})]})]})}function Wt({value:a,onChange:t,placeholder:s="Write your content here...",minHeight:r="400px",label:n,required:i=!1}){const[l,c]=m.useState("split"),[u,x]=m.useState(null),p=(y,I="")=>{if(!u)return;const U=u.selectionStart,V=u.selectionEnd,L=a.substring(U,V),G=a.substring(0,U)+y+L+I+a.substring(V);t(G),setTimeout(()=>{u.focus();const W=U+y.length+L.length;u.setSelectionRange(W,W)},0)},v=[{icon:e.jsx(Hs,{className:"w-4 h-4"}),title:"Bold",action:()=>p("**","**")},{icon:e.jsx(ia,{className:"w-4 h-4"}),title:"Italic",action:()=>p("*","*")},{icon:e.jsx(sa,{className:"w-4 h-4"}),title:"Heading",action:()=>p("## ","")},{icon:e.jsx(va,{className:"w-4 h-4"}),title:"Quote",action:()=>p("> ","")},{icon:e.jsx(Js,{className:"w-4 h-4"}),title:"Code",action:()=>p("`","`")},{icon:e.jsx(ma,{className:"w-4 h-4"}),title:"Bullet List",action:()=>p("- ","")},{icon:e.jsx(ca,{className:"w-4 h-4"}),title:"Numbered List",action:()=>p("1. ","")},{icon:e.jsx(la,{className:"w-4 h-4"}),title:"Link",action:()=>p("[","](url)")},{icon:e.jsx(ra,{className:"w-4 h-4"}),title:"Image",action:()=>p("")}];return e.jsxs("div",{className:"border rounded-lg overflow-hidden bg-background",children:[n&&e.jsxs("label",{className:"block text-sm font-medium mb-2 px-4 pt-3",children:[n," ",i&&e.jsx("span",{className:"text-destructive",children:"*"})]}),e.jsxs("div",{className:"border-b bg-muted/30 px-3 py-2 flex items-center gap-1",children:[e.jsx("div",{className:"flex items-center gap-1 flex-wrap",children:v.map((y,I)=>e.jsx("button",{type:"button",onClick:y.action,title:y.title,className:"p-2 hover:bg-background rounded transition-colors",children:y.icon},I))}),e.jsxs("div",{className:"ml-auto flex items-center gap-1 border-l pl-2",children:[e.jsx("button",{type:"button",onClick:()=>c("edit"),title:"Edit Mode",className:`p-2 rounded transition-colors ${l==="edit"?"bg-background":"hover:bg-background"}`,children:e.jsx(pa,{className:"w-4 h-4"})}),e.jsx("button",{type:"button",onClick:()=>c("split"),title:"Split View",className:`p-2 rounded transition-colors ${l==="split"?"bg-background":"hover:bg-background"}`,children:e.jsx(ya,{className:"w-4 h-4"})}),e.jsx("button",{type:"button",onClick:()=>c("preview"),title:"Preview Mode",className:`p-2 rounded transition-colors ${l==="preview"?"bg-background":"hover:bg-background"}`,children:e.jsx(Os,{className:"w-4 h-4"})})]})]}),e.jsxs("div",{className:"flex",children:[(l==="edit"||l==="split")&&e.jsx("div",{className:l==="split"?"w-1/2 border-r":"w-full",children:e.jsx("textarea",{ref:x,value:a,onChange:y=>t(y.target.value),placeholder:s,required:i,className:"w-full px-4 py-3 font-mono text-sm bg-background resize-none focus:outline-none",style:{minHeight:r}})}),(l==="preview"||l==="split")&&e.jsx("div",{className:l==="split"?"w-1/2":"w-full",children:e.jsx("div",{className:"px-4 py-3 prose prose-sm max-w-none dark:prose-invert overflow-auto",style:{minHeight:r},children:a?e.jsx(It,{remarkPlugins:[Ot],children:a}):e.jsx("p",{className:"text-muted-foreground italic",children:"Preview will appear here..."})})})]}),e.jsx("div",{className:"border-t bg-muted/20 px-4 py-2 text-xs text-muted-foreground",children:e.jsxs("details",{children:[e.jsx("summary",{className:"cursor-pointer hover:text-foreground",children:"Markdown Guide"}),e.jsxs("div",{className:"mt-2 space-y-1",children:[e.jsxs("div",{children:[e.jsx("code",{className:"bg-muted px-1 rounded",children:"**bold**"})," for ",e.jsx("strong",{children:"bold text"})]}),e.jsxs("div",{children:[e.jsx("code",{className:"bg-muted px-1 rounded",children:"*italic*"})," for ",e.jsx("em",{children:"italic text"})]}),e.jsxs("div",{children:[e.jsx("code",{className:"bg-muted px-1 rounded",children:"## Heading"})," for headings"]}),e.jsxs("div",{children:[e.jsx("code",{className:"bg-muted px-1 rounded",children:"[text](url)"})," for links"]}),e.jsxs("div",{children:[e.jsx("code",{className:"bg-muted px-1 rounded",children:""})," for images"]}),e.jsxs("div",{children:[e.jsx("code",{className:"bg-muted px-1 rounded",children:"- item"})," for bullet lists"]}),e.jsxs("div",{children:[e.jsx("code",{className:"bg-muted px-1 rounded",children:"1. item"})," for numbered lists"]}),e.jsxs("div",{children:[e.jsx("code",{className:"bg-muted px-1 rounded",children:"`code`"})," for inline code"]}
2),e.jsxs("div",{children:[e.jsx("code",{className:"bg-muted px-1 rounded",children:"```code block```"})," for code blocks"]})]})]})})]})}function Yt({type:a}){const[t,s]=m.useState([]),[r,n]=m.useState([]),[i,l]=m.useState(!0),[c,u]=m.useState(null),[x,p]=m.useState(!1),[v,y]=m.useState({}),[I,U]=m.useState(!1);m.useEffect(()=>{V(),a==="faq"&&L()},[a]);const V=async()=>{try{const{apiFetch:d}=await Y(async()=>{const{apiFetch:b}=await import("./api-CyvozDRd.js");return{apiFetch:b}},[]),k=await d(a==="blog"?"/api/admin/blog":"/api/admin/faq");s(Array.isArray(k)?k:[])}catch(d){console.error(`Error loading ${a}:`,d),s([])}finally{l(!1)}},L=async()=>{try{const{apiFetch:d}=await Y(async()=>{const{apiFetch:k}=await import("./api-CyvozDRd.js");return{apiFetch:k}},[]),C=await d("/api/admin/faq/categories");n(Array.isArray(C)?C:[])}catch(d){console.error("Error loading FAQ categories:",d),n([])}},G=async d=>{d.preventDefault();try{const{apiFetch:C}=await Y(async()=>{const{apiFetch:F}=await import("./api-CyvozDRd.js");return{apiFetch:F}},[]),k=a==="blog"?"/api/admin/blog":"/api/admin/faq",b=c?{...v,id:c}:v;await C(k,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(b)}),U(!1),u(null),y({}),V()}catch(C){console.error(`Error saving ${a}:`,C),alert(`Failed to save ${a}`)}},W=async d=>{if(confirm(`Are you sure you want to delete this ${a}?`))try{const{apiFetch:C}=await Y(async()=>{const{apiFetch:b}=await import("./api-CyvozDRd.js");return{apiFetch:b}},[]),k=a==="blog"?`/api/admin/blog/${d}`:`/api/admin/faq/${d}`;await C(k,{method:"DELETE"}),V()}catch(C){console.error(`Error deleting ${a}:`,C),alert(`Failed to delete ${a}`)}},ne=d=>{u(d.id),y(d),U(!0),p(!1)},E=d=>d.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-|-$/g,"");return i?e.jsx("div",{className:"p-4",children:"Loading..."}):e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"flex justify-between items-center",children:[e.jsx("h2",{className:"text-2xl font-bold",children:a==="blog"?"Blog Management":"FAQ Management"}),e.jsxs("button",{onClick:()=>{U(!0),u(null),y(a==="blog"?{status:"draft"}:{status:"published",display_order:0})},className:"px-4 py-2 bg-primary text-primary-foreground rounded-md hover:bg-primary/90",children:["Create New ",a==="blog"?"Post":"FAQ"]})]}),I&&e.jsx("div",{className:"fixed inset-0 bg-black/50 flex items-center justify-center z-50 p-4 overflow-y-auto",children:e.jsxs("div",{className:"bg-background rounded-lg shadow-lg max-w-4xl w-full max-h-[90vh] overflow-y-auto",children:[e.jsxs("div",{className:"sticky top-0 bg-background border-b p-4 flex justify-between items-center",children:[e.jsxs("h3",{className:"text-xl font-bold",children:[c?"Edit":"Create"," ",a==="blog"?"Post":"FAQ"]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx("button",{type:"button",onClick:()=>p(!x),className:"px-3 py-1 border rounded-md",children:x?"Edit":"Preview"}),e.jsx("button",{onClick:()=>{U(!1),y({}),u(null),p(!1)},className:"px-3 py-1 border rounded-md",children:"Close"})]})]}),e.jsx("div",{className:"p-6",children:x?e.jsx("div",{className:"prose prose-sm md:prose-lg max-w-none dark:prose-invert",children:a==="blog"?e.jsxs(e.Fragment,{children:[e.jsx("h1",{children:v.title}),v.featured_image&&e.jsx("img",{src:v.featured_image,alt:v.title,className:"w-full rounded-lg mb-4"}),v.excerpt&&e.jsx("p",{className:"text-lg text-muted-foreground italic border-l-4 border-primary pl-4 my-4",children:v.excerpt}),e.jsx(It,{remarkPlugins:[Ot],children:v.content||""})]}):e.jsxs(e.Fragment,{children:[e.jsx("h3",{className:"text-xl font-semibold mb-4",children:v.question}),e.jsx(It,{remarkPlugins:[Ot],children:v.answer||""})]})}):e.jsxs("form",{onSubmit:G,className:"space-y-4",children:[a==="blog"?e.jsxs(e.Fragment,{children:[e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-medium mb-1",children:"Title *"}),e.jsx("input",{type:"text",value:v.title||"",onChange:d=>{const C=d.target.value;y({...v,title:C,slug:E(C)})},className:"w-full border rounded-md px-3 py-2",required:!0})]}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-medium mb-1",children:"Slug *"}),e.jsx("input",{type:"text",value:v.slug||"",onChange:d=>y({...v,slug:d.target.value}),className:"w-full border rounded-md px-3 py-2",required:!0})]}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-medium mb-1",children:"Excerpt"}),e.jsx("textarea",{value:v.excerpt||"",onChange:d=>y({...v,excerpt:d.target.value}),className:"w-full border rounded-md px-3 py-2",rows:2})]}),e.jsx(Wt,{label:"Content",value:v.content||"",onChange:d=>y({...v,content:d}),placeholder:"Write your blog post content in Markdown...",minHeight:"500px",required:!0}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-medium mb-1",children:"Featured Image URL"}),e.jsx("input",{type:"url",value:v.featured_image||"",onChange:d=>y({...v,featured_image:d.target.value}),className:"w-full border rounded-md px-3 py-2"})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-medium mb-1",children:"Meta Title"}),e.jsx("input",{type:"text",value:v.meta_title||"",onChange:d=>y({...v,meta_title:d.target.value}),className:"w-full border rounded-md px-3 py-2"})]}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-medium mb-1",children:"Status *"}),e.jsxs("select",{value:v.status||"draft",onChange:d=>y({...v,status:d.target.value}),className:"w-full border rounded-md px-3 py-2",required:!0,children:[e.jsx("option",{value:"draft",children:"Draft"}),e.jsx("option",{value:"published",children:"Published"}),e.jsx("option",{value:"archived",children:"Archived"})]})]})]}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-medium mb-1",children:"Meta Description"}),e.jsx("textarea",{value:v.meta_description||"",onChange:d=>y({...v,meta_description:d.target.value}),className:"w-full border rounded-md px-3 py-2",rows:2})]}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-medium mb-1",children:"Meta Keywords"}),e.jsx("input",{type:"text",value:v.meta_keywords||"",onChange:d=>y({...v,meta_keywords:d.target.value}),className:"w-full border rounded-md px-3 py-2",placeholder:"music, lessons, guitar, piano"})]})]}):e.jsxs(e.Fragment,{children:[e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-medium mb-1",children:"Category"}),e.jsxs("select",{value:v.category_id||"",onChange:d=>y({...v,category_id:d.target.value}),className:"w-full border rounded-md px-3 py-2",children:[e.jsx("option",{value:"",children:"No Category"}),r.map(d=>e.jsx("option",{value:d.id,children:d.name},d.id))]})]}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-medium mb-1",children:"Question *"}),e.jsx("input",{type:"text",value:v.question||"",onChange:d=>y({...v,question:d.target.value}),className:"w-full border rounded-md px-3 py-2",required:!0})]}),e.jsx(Wt,{label:"Answer",value:v.answer||"",onChange:d=>y({...v,answer:d}),placeholder:"Write the FAQ answer in Markdown...",minHeight:"300px",required:!0}),e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-medium mb-1",children:"Display Order"}),e.jsx("input",{type:"number",value:v.display_order||0,onChange:d=>y({...v,display_order:parseInt(d.target.value)}),className:"w-full border rounded-md px-3 py-2"})]}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-medium mb-1",children:"Status *"}),e.jsxs("select",{value:v.status||"published",onChange:d=>y({...v,status:d.target.value}),className:"w-full border rounded-md px-3 py-2",required:!0,children:[e.jsx("option",{value:"draft",children:"Draft"}),e.jsx("option",{value:"published",children:"Published"}),e.jsx("option",{value:"archived",children:"Archived"})]})]})]})]}),e.jsxs("div",{className:"flex gap-2 pt-4",children:[e.jsx("button",{type:"submit",className:"px-4 py-2 bg-primary text-primary-foreground rounded-md hover:bg-primary/90",children:c?"Update":"Create"}),e.jsx("button",{type:"button",onClick:()=>{U(!1),y({}),u(null)},className:"px-4 py-2 border rounded-md",children:"Cancel"})]})]})})]})}),e.jsx("div",{className:"space-y-4",children:t.length===0?e.jsxs("div",{className:"text-center text-muted-foreground py-8",children:["No ",a==="blog"?"blog posts":"FAQs"," yet. Create your first one!"]}):e.jsx("div",{className:"grid gap-4",children:t.map(d=>e.jsx("div",{className:"border rounded-lg p-4 hover:shadow-md transition-shadow",children:e.jsxs("div",{className:"flex justify-between items-start",children:[e.jsxs("div",{className:"flex-1",children:[e.jsx("h3",{className:"font-semibold text-lg",children:a==="blog"?d.title:d.question}),a==="blog"&&d.excerpt&&e.jsx("p",{className:"text-sm text-muted-foreground mt-1",children:d.excerpt}),a==="faq"&&e.jsxs("p",{className:"text-sm text-muted-foreground mt-1",children:[d.answer.substring(0,150),"..."]}),e.jsxs("div",{className:"flex gap-3 mt-2 text-xs text-muted-foreground",children:[e.jsx("span",{className:`px-2 py-1 rounded ${d.status==="published"?"bg-green-100 text-green-800":d.status==="draft"?"bg-yellow-100 text-yellow-800":"bg-gray-100 text-gray-800"}`,children:d.status}),a==="blog"&&d.author_name&&e.jsxs("span",{children:["By ",d.author_name]}),a==="faq"&&d.category_name&&e.jsxs("span",{children:["Category: ",d.
2category_name]}),e.jsxs("span",{children:[d.views||0," views"]})]})]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx("button",{onClick:()=>ne(d),className:"px-3 py-1 text-sm border rounded-md hover:bg-muted",children:"Edit"}),e.jsx("button",{onClick:()=>W(d.id),className:"px-3 py-1 text-sm border border-red-300 text-red-600 rounded-md hover:bg-red-50",children:"Delete"})]})]})},d.id))})})]})}var ae;(function(a){a.assertEqual=n=>{};function t(n){}a.assertIs=t;function s(n){throw new Error}a.assertNever=s,a.arrayToEnum=n=>{const i={};for(const l of n)i[l]=l;return i},a.getValidEnumValues=n=>{const i=a.objectKeys(n).filter(c=>typeof n[n[c]]!="number"),l={};for(const c of i)l[c]=n[c];return a.objectValues(l)},a.objectValues=n=>a.objectKeys(n).map(function(i){return n[i]}),a.objectKeys=typeof Object.keys=="function"?n=>Object.keys(n):n=>{const i=[];for(const l in n)Object.prototype.hasOwnProperty.call(n,l)&&i.push(l);return i},a.find=(n,i)=>{for(const l of n)if(i(l))return l},a.isInteger=typeof Number.isInteger=="function"?n=>Number.isInteger(n):n=>typeof n=="number"&&Number.isFinite(n)&&Math.floor(n)===n;function r(n,i=" | "){return n.map(l=>typeof l=="string"?`'${l}'`:l).join(i)}a.joinValues=r,a.jsonStringifyReplacer=(n,i)=>typeof i=="bigint"?i.toString():i})(ae||(ae={}));var Jt;(function(a){a.mergeShapes=(t,s)=>({...t,...s})})(Jt||(Jt={}));const O=ae.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),De=a=>{switch(typeof a){case"undefined":return O.undefined;case"string":return O.string;case"number":return Number.isNaN(a)?O.nan:O.number;case"boolean":return O.boolean;case"function":return O.function;case"bigint":return O.bigint;case"symbol":return O.symbol;case"object":return Array.isArray(a)?O.array:a===null?O.null:a.then&&typeof a.then=="function"&&a.catch&&typeof a.catch=="function"?O.promise:typeof Map<"u"&&a instanceof Map?O.map:typeof Set<"u"&&a instanceof Set?O.set:typeof Date<"u"&&a
vendor: 45,261 bytes, line 2
2instanceof Date?O.date:O.object;default:return O.unknown}},j=ae.arrayToEnum(["invalid_type","invalid_literal","custom","invalid_union","invalid_union_discriminator","invalid_enum_value","unrecognized_keys","invalid_arguments","invalid_return_type","invalid_date","invalid_string","too_small","too_big","invalid_intersection_types","not_multiple_of","not_finite"]);class Oe extends Error{get errors(){return this.issues}constructor(t){super(),this.issues=[],this.addIssue=r=>{this.issues=[...this.issues,r]},this.addIssues=(r=[])=>{this.issues=[...this.issues,...r]};const s=new.target.prototype;Object.setPrototypeOf?Object.setPrototypeOf(this,s):this.__proto__=s,this.name="ZodError",this.issues=t}format(t){const s=t||function(i){return i.message},r={_errors:[]},n=i=>{for(const l of i.issues)if(l.code==="invalid_union")l.unionErrors.map(n);else if(l.code==="invalid_return_type")n(l.returnTypeError);else if(l.code==="invalid_arguments")n(l.argumentsError);else if(l.path.length===0)r._errors.push(s(l));else{let c=r,u=0;for(;u<l.path.length;){const x=l.path[u];u===l.path.length-1?(c[x]=c[x]||{_errors:[]},c[x]._errors.push(s(l))):c[x]=c[x]||{_errors:[]},c=c[x],u++}}};return n(this),r}static assert(t){if(!(t instanceof Oe))throw new Error(`Not a ZodError: ${t}`)}toString(){return this.message}get message(){return JSON.stringify(this.issues,ae.jsonStringifyReplacer,2)}get isEmpty(){return this.issues.length===0}flatten(t=s=>s.message){const s={},r=[];for(const n of this.issues)if(n.path.length>0){const i=n.path[0];s[i]=s[i]||[],s[i].push(t(n))}else r.push(t(n));return{formErrors:r,fieldErrors:s}}get formErrors(){return this.flatten()}}Oe.create=a=>new Oe(a);const Lt=(a,t)=>{let s;switch(a.code){case j.invalid_type:a.received===O.undefined?s="Required":s=`Expected ${a.expected}, received ${a.received}`;break;case j.invalid_literal:s=`Invalid literal value, expected ${JSON.stringify(a.expected,ae.jsonStringifyReplacer)}`;break;case j.unrecognized_keys:s=`Unrecognized key(s) in object: ${ae.joinValues(a.keys,", ")}`;break;case j.invalid_union:s="Invalid input";break;case j.invalid_union_discriminator:s=`Invalid discriminator value. Expected ${ae.joinValues(a.options)}`;break;case j.invalid_enum_value:s=`Invalid enum value. Expected ${ae.joinValues(a.options)}, received '${a.received}'`;break;case j.invalid_arguments:s="Invalid function arguments";break;case j.invalid_return_type:s="Invalid function return type";break;case j.invalid_date:s="Invalid date";break;case j.invalid_string:typeof a.validation=="object"?"includes"in a.validation?(s=`Invalid input: must include "${a.validation.includes}"`,typeof a.validation.position=="number"&&(s=`${s} at one or more positions greater than or equal to ${a.validation.position}`)):"startsWith"in a.validation?s=`Invalid input: must start with "${a.validation.startsWith}"`:"endsWith"in a.validation?s=`Invalid input: must end with "${a.validation.endsWith}"`:ae.assertNever(a.validation):a.validation!=="regex"?s=`Invalid ${a.validation}`:s="Invalid";break;case j.too_small:a.type==="array"?s=`Array must contain ${a.exact?"exactly":a.inclusive?"at least":"more than"} ${a.minimum} element(s)`:a.type==="string"?s=`String must contain ${a.exact?"exactly":a.inclusive?"at least":"over"} ${a.minimum} character(s)`:a.type==="number"?s=`Number must be ${a.exact?"exactly equal to ":a.inclusive?"greater than or equal to ":"greater than "}${a.minimum}`:a.type==="bigint"?s=`Number must be ${a.exact?"exactly equal to ":a.inclusive?"greater than or equal to ":"greater than "}${a.minimum}`:a.type==="date"?s=`Date must be ${a.exact?"exactly equal to ":a.inclusive?"greater than or equal to ":"greater than "}${new Date(Number(a.minimum))}`:s="Invalid input";break;case j.too_big:a.type==="array"?s=`Array must contain ${a.exact?"exactly":a.inclusive?"at most":"less than"} ${a.maximum} element(s)`:a.type==="string"?s=`String must contain ${a.exact?"exactly":a.inclusive?"at most":"under"} ${a.maximum} character(s)`:a.type==="number"?s=`Number must be ${a.exact?"exactly":a.inclusive?"less than or equal to":"less than"} ${a.maximum}`:a.type==="bigint"?s=`BigInt must be ${a.exact?"exactly":a.inclusive?"less than or equal to":"less than"} ${a.maximum}`:a.type==="date"?s=`Date must be ${a.exact?"exactly":a.inclusive?"smaller than or equal to":"smaller than"} ${new Date(Number(a.maximum))}`:s="Invalid input";break;case j.custom:s="Invalid input";break;case j.invalid_intersection_types:s="Intersection results could not be merged";break;case j.not_multiple_of:s=`Number must be a multiple of ${a.multipleOf}`;break;case j.not_finite:s="Number must be finite";break;default:s=t.defaultError,ae.assertNever(a)}return{message:s}};let Ra=Lt;function Ia(){return Ra}const Oa=a=>{const{data:t,path:s,errorMaps:r,issueData:n}=a,i=[...s,...n.path||[]],l={...n,path:i};if(n.message!==void 0)return{...n,path:i,message:n.message};let c="";const u=r.filter(x=>!!x).slice().reverse();for(const x of u)c=x(l,{data:t,defaultError:c}).message;return{...n,path:i,message:c}};function P(a,t){const s=Ia(),r=Oa({issueData:t,data:a.data,path:a.path,errorMaps:[a.common.contextualErrorMap,a.schemaErrorMap,s,s===Lt?void 0:Lt].filter(n=>!!n)});a.common.issues.push(r)}class ke{constructor(){this.value="valid"}dirty(){this.value==="valid"&&(this.value="dirty")}abort(){this.value!=="aborted"&&(this.value="aborted")}static mergeArray(t,s){const r=[];for(const n of s){if(n.status==="aborted")return B;n.status==="dirty"&&t.dirty(),r.push(n.value)}return{status:t.value,value:r}}static async mergeObjectAsync(t,s){const r=[];for(const n of s){const i=await n.key,l=await n.value;r.push({key:i,value:l})}return ke.mergeObjectSync(t,r)}static mergeObjectSync(t,s){const r={};for(const n of s){const{key:i,value:l}=n;if(i.status==="aborted"||l.status==="aborted")return B;i.status==="dirty"&&t.dirty(),l.status==="dirty"&&t.dirty(),i.value!=="__proto__"&&(typeof l.value<"u"||n.alwaysSet)&&(r[i.value]=l.value)}return{status:t.value,value:r}}}const B=Object.freeze({status:"aborted"}),dt=a=>({status:"dirty",value:a}),Te=a=>({status:"valid",value:a}),Qt=a=>a.status==="aborted",Kt=a=>a.status==="dirty",Qe=a=>a.status==="valid",bt=a=>typeof Promise<"u"&&a instanceof Promise;var D;(function(a){a.errToObj=t=>typeof t=="string"?{message:t}:t||{},a.toString=t=>typeof t=="string"?t:t?.message})(D||(D={}));class Ue{constructor(t,s,r,n){this._cachedPath=[],this.parent=t,this.data=s,this._path=r,this._key=n}get path(){return this._cachedPath.length||(Array.isArray(this._key)?this._cachedPath.push(...this._path,...this._key):this._cachedPath.push(...this._path,this._key)),this._cachedPath}}const Xt=(a,t)=>{if(Qe(t))return{success:!0,data:t.value};if(!a.common.issues.length)throw new Error("Validation failed but no issues detected.");return{success:!1,get error(){if(this._error)return this._error;const s=new Oe(a.common.issues);return this._error=s,this._error}}};function J(a){if(!a)return{};const{errorMap:t,invalid_type_error:s,required_error:r,description:n}=a;if(t&&(s||r))throw new Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);return t?{errorMap:t,description:n}:{errorMap:(l,c)=>{const{message:u}=a;return l.code==="invalid_enum_value"?{message:u??c.defaultError}:typeof c.data>"u"?{message:u??r??c.defaultError}:l.code!=="invalid_type"?{message:c.defaultError}:{message:u??s??c.defaultError}},description:n}}class se{get description(){return this._def.description}_getType(t){return De(t.data)}_getOrReturnCtx(t,s){return s||{common:t.parent.common,data:t.data,parsedType:De(t.data),schemaErrorMap:this._def.errorMap,path:t.path,parent:t.parent}}_processInputParams(t){return{status:new ke,ctx:{common:t.parent.common,data:t.data,parsedType:De(t.data),schemaErrorMap:this._def.errorMap,path:t.path,parent:t.parent}}}_parseSync(t){const s=this._parse(t);if(bt(s))throw new Error("Synchronous parse encountered promise.");return s}_parseAsync(t){const s=this._parse(t);return Promise.resolve(s)}parse(t,s){const r=this.safeParse(t,s);if(r.success)return r.data;throw r.error}safeParse(t,s){const r={common:{issues:[],async:s?.async??!1,contextualErrorMap:s?.errorMap},path:s?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:t,parsedType:De(t)},n=this._parseSync({data:t,path:r.path,parent:r});return Xt(r,n)}"~validate"(t){const s={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:t,parsedType:De(t)};if(!this["~standard"].async)try{const r=this._parseSync({data:t,path:[],parent:s});return Qe(r)?{value:r.value}:{issues:s.common.issues}}catch(r){r?.message?.toLowerCase()?.includes("encountered")&&(this["~standard"].async=!0),s.common={issues:[],async:!0}}return this._parseAsync({data:t,path:[],parent:s}).then(r=>Qe(r)?{value:r.value}:{issues:s.common.issues})}async parseAsync(t,s){const r=await this.safeParseAsync(t,s);if(r.success)return r.data;throw r.error}async safeParseAsync(t,s){const r={common:{issues:[],contextualErrorMap:s?.errorMap,async:!0},path:s?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:t,parsedType:De(t)},n=this._parse({data:t,path:r.path,parent:r}),i=await(bt(n)?n:Promise.resolve(n));return Xt(r,i)}refine(t,s){const r=n=>typeof s=="string"||typeof s>"u"?{message:s}:typeof s=="function"?s(n):s;return this._refinement((n,i)=>{const l=t(n),c=()=>i.addIssue({code:j.custom,...r(n)});return typeof Promise<"u"&&l instanceof Promise?l.then(u=>u?!0:(c(),!1)):l?!0:(c(),!1)})}refinement(t,s){return this._refinement((r,n)=>t(r)?!0:(n.addIssue(typeof s=="function"?s(r,n):s),!1))}_refinement(t){return new et({schema:this,typeName:H.ZodEffects,effect:{type:"refinement",refinement:t}})}superRefine(t){return this._refinement(t)}constructor(t){this.spa=this.safeParseAsync,this._def=t,this.parse=this.parse.bind(this),this.safeParse=this.safeParse.bind(this),this.parseAsync=this.parseAsync.bind(this),this.safeParseAsync=this.safeParseAsync.bind(this),this.spa=this.spa.bind(this),this.refine=this.refine.bind(this),this.refinement=this.refinement.bind(this),this.superRefine=this.superRefine.bind(this),this.optional=this.optional.bind(this),this.nullable=this.nullable.bind(this),this.nullish=this.nullish.bind(this),this.array=this.array.bind(this),this.promise=this.promise.bind(this),this.or=this.or.bind(this),this.and=this.and.bind(this),this.transform=this.transform.bind(this),this.brand=this.brand.bind(this),this.default=this.default.bind(this),this.catch=this.catch.bind(this),this.describe=this.describe.bind(this),this.pipe=this.pipe.bind(this),this.readonly=this.readonly.bind(this),this.isNullable=this.isNullable.bind(this),this.isOptional=this.isOptional.bind(this),this["~standard"]={version:1,vendor:"zod",validate:s=>this["~validate"](s)}}optional(){return ze.create(this,this._def)}nullable(){return tt.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return Ae.create(this)}promise(){return wt.create(this,this._def)}or(t){return jt.create([this,t],this._def)}and(t){return Nt.create(this,t,this._def)}transform(t){return new et({...J(this._def),schema:this,typeName:H.ZodEffects,effect:{type:"transform",transform:t}})}default(t){const s=typeof t=="function"?t:()=>t;return new Mt({...J(this._def),innerType:this,defaultValue:s,typeName:H.ZodDefault})}brand(){return new rr({typeName:H.ZodBranded,type:this,...J(this._def)})}catch(t){const s=typeof t=="function"?t:()=>t;return new $t({...J(this._def),innerType:this,catchValue:s,typeName:H.ZodCatch})}describe(t){const s=this.constructor;return new s({...this._def,description:t})}pipe(t){return Ut.create(this,t)}readonly(){return zt.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}}const La=/^c[^\s-]{8,}$/i,Da=/^[0-9a-z]+$/,Ma=/^[0-9A-HJKMNP-TV-Z]{26}$/i,$a=/^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/i,za=/^[a-z0-9_-]{21}$/i,Ua=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,Va=/^[-+]?P(?!$)(?:(?:[-+]?\d+Y)|(?:[-+]?\d+[.,]\d+Y$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:(?:[-+]?\d+W)|(?:[-+]?\d+[.,]\d+W$))?(?:(?:[-+]?\d+D)|(?:[-+]?\d+[.,]\d+D$))?(?:T(?=[\d+-])(?:(?:[-+]?\d+H)|(?:[-+]?\d+[.,]\d+H$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:[-+]?\d+(?:[.,]\d+)?S)?)??$/,Za=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,qa="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$";let Ft;const Ba=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,Ha=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/(3[0-2]|[12]?[0-9])$/,Ga=/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))$/,Wa=/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,Ya=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,Ja=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,gs="((\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-((0[13578]|1[02])-(0[1-9]|[12]\\d|3[01])|(0[469]|11)-(0[1-9]|[12]\\d|30)|(02)-(0[1-9]|1\\d|2[0-8])))",Qa=new RegExp(`^${gs}$`);function vs(a){let t="[0-5]\\d";a.precision?t=`${t}\\.\\d{${a.precision}}`:a.precision==null&&(t=`${t}(\\.\\d+)?`);const s=a.precision?"+":"?";return`([01]\\d|2[0-3]):[0-5]\\d(:${t})${s}`}function Ka(a){return new RegExp(`^${vs(a)}$`)}function Xa(a){let t=`${gs}T${vs(a)}`;const s=[];return s.push(a.local?"Z?":"Z"),a.offset&&s.push("([+-]\\d{2}:?\\d{2})"),t=`${t}(${s.join("|")})`,new RegExp(`^${t}$`)}function er(a,t){return!!((t==="v4"||!t)&&Ba.test(a)||(t==="v6"||!t)&&Ga.test(a))}function tr(a,t){if(!Ua.test(a))return!1;try{const[s]=a.split(".");if(!s)return!1;const r=s.replace(/-/g,"+").replace(/_/g,"/").padEnd(s.length+(4-s.length%4)%4,"="),n=JSON.parse(atob(r));return!(typeof n!="object"||n===null||"typ"in n&&n?.typ!=="JWT"||!n.alg||t&&n.alg!==t)}catch{return!1}}function sr(a,t){return!!((t==="v4"||!t)&&Ha.test(a)||(t==="v6"||!t)&&Wa.test(a))}class $e extends se{_parse(t){if(this._def.coerce&&(t.data=String(t.data)),this._getType(t)!==O.string){const i=this._getOrReturnCtx(t);return P(i,{code:j.invalid_type,expected:O.string,received:i.parsedType}),B}const r=new ke;let n;for(const i of this._def.checks)if(i.kind==="min")t.data.length<i.value&&(n=this._getOrReturnCtx(t,n),P(n,{code:j.too_small,minimum:i.value,type:"string",inclusive:!0,exact:!1,message:i.message}),r.dirty());else if(i.kind==="max")t.data.length>i.value&&(n=this._getOrReturnCtx(t,n),P(n,{code:j.too_big,maximum:i.value,type:"string",inclusive:!0,exact:!1,message:i.message}),r.dirty());else if(i.kind==="length"){const l=t.data.length>i.value,c=t.data.length<i.value;(l||c)&&(n=this._getOrReturnCtx(t,n),l?P(n,{code:j.too_big,maximum:i.value,type:"string",inclusive:!0,exact:!0,message:i.message}):c&&P(n,{code:j.too_small,minimum:i.value,type:"string",inclusive:!0,exact:!0,message:i.message}),r.dirty())}else if(i.kind==="email")Za.test(t.data)||(n=this._getOrReturnCtx(t,n),P(n,{validation:"email",code:j.invalid_string,message:i.message}),r.dirty());else if(i.kind==="emoji")Ft||(Ft=new RegExp(qa,"u")),Ft.test(t.data)||(n=this._getOrReturnCtx(t,n),P(n,{validation:"emoji",code:j.invalid_string,message:i.message}),r.dirty());else if(i.kind==="uuid")$a.test(t.data)||(n=this._getOrReturnCtx(t,n),P(n,{validation:"uuid",code:j.invalid_string,message:i.message}),r.dirty());else if(i.kind==="nanoid")za.test(t.data)||(n=this._getOrReturnCtx(t,n),P(n,{validation:"nanoid",code:j.invalid_string,message:i.message}),r.dirty());else if(i.kind==="cuid")La.test(t.data)||(n=this._getOrReturnCtx(t,n),P(n,{validation:"cuid",code:j.invalid_string,message:i.message}),r.dirty());else if(i.kind==="cuid2")Da.test(t.data)||(n=this._getOrReturnCtx(t,n),P(n,{validation:"cuid2",code:j.invalid_string,message:i.message}),r.dirty());else if(i.kind==="ulid")Ma.test(t.data)||(n=this._getOrReturnCtx(t,n),P(n,{validation:"ulid",code:j.invalid_string,message:i.message}),r.dirty());else if(i.kind==="url")try{new URL(t.data)}catch{n=this._getOrReturnCtx(t,n),P(n,{validation:"url",code:j.invalid_string,message:i.message}),r.dirty()}else i.kind==="regex"?(i.regex.lastIndex=0,i.regex.test(t.data)||(n=this._getOrReturnCtx(t,n),P(n,{validation:"regex",code:j.invalid_string,message:i.message}),r.dirty())):i.kind==="trim"?t.data=t.data.trim():i.kind==="includes"?t.data.includes(i.value,i.position)||(n=this._getOrReturnCtx(t,n),P(n,{code:j.invalid_string,validation:{includes:i.value,position:i.position},message:i.message}),r.dirty()):i.kind==="toLowerCase"?t.data=t.data.toLowerCase():i.kind==="toUpperCase"?t.data=t.data.toUpperCase():i.kind==="startsWith"?t.data.startsWith(i.value)||(n=this._getOrReturnCtx(t,n),P(n,{code:j.invalid_string,validation:{startsWith:i.value},message:i.message}),r.dirty()):i.kind==="endsWith"?t.data.endsWith(i.value)||(n=this._getOrReturnCtx(t,n),P(n,{code:j.invalid_string,validation:{endsWith:i.value},message:i.message}),r.dirty()):i.kind==="datetime"?Xa(i).test(t.data)||(n=this._getOrReturnCtx(t,n),P(n,{code:j.invalid_string,validation:"datetime",message:i.message}),r.dirty()):i.kind==="date"?Qa.test(t.data)||(n=this._getOrReturnCtx(t,n),P(n,{code:j.invalid_string,validation:"date",message:i.message}),r.dirty()):i.kind==="time"?Ka(i).test(t.data)||(n=this._getOrReturnCtx(t,n),P(n,{code:j.invalid_string,validation:"time",message:i.message}),r.dirty()):i.kind==="duration"?Va.test(t.data)||(n=this._getOrReturnCtx(t,n),P(n,{validation:"duration",code:j.invalid_string,message:i.message}),r.dirty()):i.kind==="ip"?er(t.data,i.version)||(n=this._getOrReturnCtx(t,n),P(n,{validation:"ip",code:j.invalid_string,message:i.message}),r.dirty()):i.kind==="jwt"?tr(t.data,i.alg)||(n=this._getOrReturnCtx(t,n),P(n,{validation:"jwt",code:j.invalid_string,message:i.message}),r.dirty()):i.kind==="cidr"?sr(t.data,i.version)||(n=this._getOrReturnCtx(t,n),P(n,{validation:"cidr",code:j.invalid_string,message:i.message}),r.dirty()):i.kind==="base64"?Ya.test(t.data)||(n=this._getOrReturnCtx(t,n),P(n,{validation:"base64",code:j.invalid_string,message:i.message}),r.dirty()):i.kind==="base64url"?Ja.test(t.data)||(n=this._getOrReturnCtx(t,n),P(n,{validation:"base64url",code:j.invalid_string,message:i.message}),r.dirty()):ae.assertNever(i);return{status:r.value,value:t.data}}_regex(t,s,r){return this.refinement(n=>t.test(n),{validation:s,code:j.invalid_string,...D.errToObj(r)})}_addCheck(t){return new $e({...this._def,checks:[...this._def.checks,t]})}email(t){return this._addCheck({kind:"email",...D.errToObj(t)})}url(t){return this._addCheck({kind:"url",...D.errToObj(t)})}emoji(t){return this._addCheck({kind:"emoji",...D.errToObj(t)})}uuid(t){return this._addCheck({kind:"uuid",...D.errToObj(t)})}nanoid(t){return this._addCheck({kind:"nanoid",...D.errToObj(t)})}cuid(t){return this._addCheck({kind:"cuid",...D.errToObj(t)})}cuid2(t){return this._addCheck({kind:"cuid2",...D.errToObj(t)})}ulid(t){return this._addCheck({kind:"ulid",...D.errToObj(t)})}base64(t){return this._addCheck({kind:"base64",...D.errToObj(t)})}base64url(t){return this._addCheck({kind:"base64url",...D.errToObj(t)})}jwt(t){return this._addCheck({kind:"jwt",...D.errToObj(t)})}ip(t){return this._addCheck({kind:"ip",...D.errToObj(t)})}cidr(t){return this._addCheck({kind:"cidr",...D.errToObj(t)})}datetime(t){return typeof t=="string"?this._addCheck({kind:"datetime",precision:null,offset:!1,local:!1,message:t}):this._addCheck({kind:"datetime",precision:typeof t?.precision>"u"?null:t?.precision,offset:t?.offset??!1,local:t?.local??!1,...D.errToObj(t?.message)})}date(t){return this._addCheck({kind:"date",message:t})}time(t){return typeof t=="string"?this._addCheck({kind:"time",precision:null,message:t}):this._addCheck({kind:"time",precision:typeof t?.precision>"u"?null:t?.precision,...D.errToObj(t?.message)})}duration(t){return this._addCheck({kind:"duration",...D.errToObj(t)})}regex(t,s){return this._addCheck({kind:"regex",regex:t,...D.errToObj(s)})}includes(t,s){return this._addCheck({kind:"includes",value:t,position:s?.position,...D.errToObj(s?.message)})}startsWith(t,s){return this._addCheck({kind:"startsWith",value:t,...D.errToObj(s)})}endsWith(t,s){return this._addCheck({kind:"endsWith",value:t,...D.errToObj(s)})}min(t,s){return this._addCheck({kind:"min",value:t,...D.errToObj(s)})}max(t,s){return this._addCheck({kind:"max",value:t,...D.errToObj(s)})}length(t,s){return this._addCheck({kind:"length",value:t,...D.errToObj(s)})}nonempty(t){return this.min(1,D.errToObj(t))}trim(){return new $e({...this._def,checks:[...this._def.checks,{kind:"trim"}]})}toLowerCase(){return new $e({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]})}toUpperCase(){return new $e({...this._def,checks:[...this._def.checks,{kind:"toUpperCase"}]})}get isDatetime(){return!!this._def.checks.find(t=>t.kind==="datetime")}get isDate(){return!!this._def.checks.find(t=>t.kind==="date")}get isTime(){return!!this._def.checks.find(t=>t.kind==="time")}get isDuration(){return!!this._def.checks.find(t=>t.kind==="duration")}get isEmail(){return!!this._def.checks.find(t=>t.kind==="email")}get isURL(){return!!this._def.checks.find(t=>t.kind==="url")}get isEmoji(){return!!this._def.checks.find(t=>t.kind==="emoji")}get isUUID(){return!!this._def.checks.find(t=>t.kind==="uuid")}get isNANOID(){return!!this._def.checks.find(t=>t.kind==="nanoid")}get isCUID(){return!!this._def.checks.find(t=>t.kind==="cuid")}get isCUID2(){return!!this._def.checks.find(t=>t.kind==="cuid2")}get isULID(){return!!this._def.checks.find(t=>t.kind==="ulid")}get isIP(){return!!this._def.checks.find(t=>t.kind==="ip")}get isCIDR(){return!!this._def.checks.find(t=>t.kind==="cidr")}get isBase64(){return!!this._def.checks.find(t=>t.kind==="base64")}get isBase64url(){return!!this._def.checks.find(t=>t.kind==="base64url")}get minLength(){let t=null;for(const s of this._def.checks)s.kind==="min"&&(t===null||s.value>t)&&(t=s.value);return t}get maxLength(){let t=null;for(const s of this._def.checks)s.kind==="max"&&(t===null||s.value<t)&&(t=s.value);return t}}$e.create=a=>new $e({checks:[],typeName:H.ZodString,coerce:a?.coerce??!1,...J(a)});function ar(a,t){const s=(a.toString().split(".")[1]||"").length,r=(t.toString().split(".")[1]||"").length,n=s>r?s:r,i=Number.parseInt(a.toFixed(n).replace(".","")),l=Number.parseInt(t.toFixed(n).replace(".",""));return i%l/10**n}class Ke extends se{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte,this.step=this.multipleOf}_parse(t){if(this._def.coerce&&(t.data=Number(t.data)),this._getType(t)!==O.number){const i=this._getOrReturnCtx(t);return P(i,{code:j.invalid_type,expected:O.number,received:i.parsedType}),B}let r;const n=new ke;for(const i of this._def.checks)i.kind==="int"?ae.isInteger(t.data)||(r=this._getOrReturnCtx(t,r),P(r,{code:j.invalid_type,expected:"integer",received:"float",message:i.message}),n.dirty()):i.kind==="min"?(i.inclusive?t.data<i.value:t.data<=i.value)&&(r=this._getOrReturnCtx(t,r),P(r,{code:j.too_small,minimum:i.value,type:"number",inclusive:i.inclusive,exact:!1,message:i.message}),n.dirty()):i.kind==="max"?(i.inclusive?t.data>i.value:t.data>=i.value)&&(r=this._getOrReturnCtx(t,r),P(r,{code:j.too_big,maximum:i.value,type:"number",inclusive:i.inclusive,exact:!1,message:i.message}),n.dirty()):i.kind==="multipleOf"?ar(t.data,i.value)!==0&&(r=this._getOrReturnCtx(t,r),P(r,{code:j.not_multiple_of,multipleOf:i.value,message:i.message}),n.dirty()):i.kind==="finite"?Number.isFinite(t.data)||(r=this._getOrReturnCtx(t,r),P(r,{code:j.not_finite,message:i.message}),n.dirty()):ae.assertNever(i);return{status:n.value,value:t.data}}gte(t,s){return this.setLimit("min",t,!0,D.toString(s))}gt(t,s){return this.setLimit("min",t,!1,D.toString(s))}lte(t,s){return this.setLimit("max",t,!0,D.toString(s))}lt(t,s){return this.setLimit("max",t,!1,D.toString(s))}setLimit(t,s,r,n){return new Ke({...this._def,checks:[...this._def.checks,{kind:t,value:s,inclusive:r,message:D.toString(n)}]})}_addCheck(t){return new Ke({...this._def,checks:[...this._def.checks,t]})}int(t){return this._addCheck({kind:"int",message:D.toString(t)})}positive(t){return this._addCheck({kind:"min",value:0,inclusive:!1,message:D.toString(t)})}negative(t){return this._addCheck({kind:"max",value:0,inclusive:!1,message:D.toString(t)})}nonpositive(t){return this._addCheck({kind:"max",value:0,inclusive:!0,message:D.toString(t)})}nonnegative(t){return this._addCheck({kind:"min",value:0,inclusive:!0,message:D.toString(t)})}multipleOf(t,s){return this._addCheck({kind:"multipleOf",value:t,message:D.toString(s)})}finite(t){return this._addCheck({kind:"finite",message:D.toString(t)})}safe(t){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:D.toString(t)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:D.toString(t)})}get minValue(){let t=null;for(const s of this._def.checks)s.kind==="min"&&(t===null||s.value>t)&&(t=s.value);return t}get maxValue(){let t=null;for(const s of this._def.checks)s.kind==="max"&&(t===null||s.value<t)&&(t=s.value);return t}get isInt(){return!!this._def.checks.find(t=>t.kind==="int"||t.kind==="multipleOf"&&ae.isInteger(t.value))}get isFinite(){let t=null,s=null;for(const r of this._def.checks){if(r.kind==="finite"||r.kind==="int"||r.kind==="multipleOf")return!0;r.kind==="min"?(s===null||r.value>s)&&(s=r.value):r.kind==="max"&&(t===null||r.value<t)&&(t=r.value)}return Number.isFinite(s)&&Number.isFinite(t)}}Ke.create=a=>new Ke({checks:[],typeName:H.ZodNumber,coerce:a?.coerce||!1,...J(a)});class ct extends se{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte}_parse(t){if(this._def.coerce)try{t.data=BigInt(t.data)}catch{return this._getInvalidInput(t)}if(this._getType(t)!==O.bigint)return this._getInvalidInput(t);let r;const n=new ke;for(const i of this._def.checks)i.kind==="min"?(i.inclusive?t.data<i.value:t.data<=i.value)&&(r=this._getOrReturnCtx(t,r),P(r,{code:j.too_small,type:"bigint",minimum:i.value,inclusive:i.inclusive,message:i.message}),n.dirty()):i.kind==="max"?(i.inclusive?t.data>i.value:t.data>=i.value)&&(r=this._getOrReturnCtx(t,r),P(r,{code:j.too_big,type:"bigint",maximum:i.value,inclusive:i.inclusive,message:i.message}),n.dirty()):i.kind==="multipleOf"?t.data%i.value!==BigInt(0)&&(r=this._getOrReturnCtx(t,r),P(r,{code:j.not_multiple_of,multipleOf:i.value,message:i.message}),n.dirty()):ae.assertNever(i);return{status:n.value,value:t.data}}_getInvalidInput(t){const s=this._getOrReturnCtx(t);return P(s,{code:j.invalid_type,expected:O.bigint,received:s.parsedType}),B}gte(t,s){return this.setLimit("min",t,!0,D.toString(s))}gt(t,s){return this.setLimit("min",t,!1,D.toString(s))}lte(t,s){return this.setLimit("max",t,!0,D.toString(s))}lt(t,s){return this.setLimit("max",t,!1,D.toString(s))}setLimit(t,s,r,n){return new ct({...this._def,checks:[...this._def.checks,{kind:t,value:s,inclusive:r,message:D.toString(n)}]})}_addCheck(t){return new ct({...this._def,checks:[...this._def.checks,t]})}positive(t){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!1,message:D.toString(t)})}negative(t){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:D.toString(t)})}nonpositive(t){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:D.toString(t)})}nonnegative(t){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:D.toString(t)})}multipleOf(t,s){return this._addCheck({kind:"multipleOf",value:t,message:D.toString(s)})}get minValue(){let t=null;for(const s of this._def.checks)s.kind==="min"&&(t===null||s.value>t)&&(t=s.value);return t}get maxValue(){let t=null;for(const s of this._def.checks)s.kind==="max"&&(t===null||s.value<t)&&(t=s.value);return t}}ct.create=a=>new ct({checks:[],typeName:H.ZodBigInt,coerce:a?.coerce??!1,...J(a)});class es extends se{_parse(t){if(this._def.coerce&&(t.data=!!t.data),this._getType(t)!==O.boolean){const r=this._getOrReturnCtx(t);return P(r,{code:j.invalid_type,expected:O.boolean,received:r.parsedType}),B}return Te(t.data)}}es.create=a=>new es({typeName:H.ZodBoolean,coerce:a?.coerce||!1,...J(a)});class yt extends se{_parse(t){if(this._def.coerce&&(t.data=new Date(t.data)),this._getType(t)!==O.date){const i=this._getOrReturnCtx(t);return P(i,{code:j.invalid_type,expected:O.date,received:i.parsedType}),B}if(Number.isNaN(t.data.getTime())){const i=this._getOrReturnCtx(t);return P(i,{code:j.invalid_date}),B}const r=new ke;let n;for(const i of this._def.checks)i.kind==="min"?t.data.getTime()<i.value&&(n=this._getOrReturnCtx(t,n),P(n,{code:j.too_small,message:i.message,inclusive:!0,exact:!1,minimum:i.value,type:"date"}),r.dirty()):i.kind==="max"?t.data.getTime()>i.value&&(n=this._getOrReturnCtx(t,n),P(n,{code:j.too_big,message:i.message,inclusive:!0,exact:!1,maximum:i.value,type:"date"}),r.dirty()):ae.assertNever(i);return{status:r.value,value:new Date(t.data.getTime())}}_addCheck(t){return new yt({...this._def,checks:[...this._def.checks,t]})}min(t,s){return this._addCheck({kind:"min",value:t.getTime(),message:D.toString(s)})}max(t,s){return this._addCheck({kind:"max",value:t.getTime(),message:D.toString(s)})}get minDate(){let t=null;for(const s of this._def.checks)s.kind==="min"&&(t===null||s.value>t)&&(t=s.value);return t!=null?new Date(t):null}get maxDate(){let t=null;for(const s of this._def.checks)s.kind==="max"&&(t===null||s.value<t)&&(t=s.value);return t!=null?new Date(t):null}}yt.create=a=>new yt({checks:[],coerce:a?.coerce||!1,typeName:H.ZodDate,...J(a)});class ts extends se{_parse(t){if(this._getType(t)!==O.symbol){const r=this._getOrReturnCtx(t);return P(r,{code:j.invalid_type,expected:O.symbol,received:r.parsedType}),B}return Te(t.data)}}ts.create=a=>new ts({typeName:H.ZodSymbol,...J(a)});class ss extends se{_parse(t){if(this._getType(t)!==O.undefined){const r=this._getOrReturnCtx(t);return P(r,{code:j.invalid_type,expected:O.undefined,received:r.parsedType}),B}return Te(t.data)}}ss.create=a=>new ss({typeName:H.ZodUndefined,...J(a)});class as extends se{_parse(t){if(this._getType(t)!==O.null){const r=this._getOrReturnCtx(t);return P(r,{code:j.invalid_type,expected:O.null,received:r.parsedType}),B}return Te(t.data)}}as.create=a=>new as({typeName:H.ZodNull,...J(a)});class rs extends se{constructor(){super(...arguments),this._any=!0}_parse(t){return Te(t.data)}}rs.create=a=>new rs({typeName:H.ZodAny,...J(a)});class ns extends se{constructor(){super(...arguments),this._unknown=!0}_parse(t){return Te(t.data)}}ns.create=a=>new ns({typeName:H.ZodUnknown,...J(a)});class Ve extends se{_parse(t){const s=this._getOrReturnCtx(t);return P(s,{code:j.invalid_type,expected:O.never,received:s.parsedType}),B}}Ve.create=a=>new Ve({typeName:H.ZodNever,...J(a)});class is extends se{_parse(t){if(this._getType(t)!==O.undefined){const r=this._getOrReturnCtx(t);return P(r,{code:j.invalid_type,expected:O.void,received:r.parsedType}),B}return Te(t.data)}}is.create=a=>new is({typeName:H.ZodVoid,...J(a)});class Ae extends se{_parse(t){const{ctx:s,status:r}=this._processInputParams(t),n=this._def;if(s.parsedType!==O.array)return P(s,{code:j.invalid_type,expected:O.array,received:s.parsedType}),B;if(n.exactLength!==null){const l=s.data.length>n.exactLength.value,c=s.data.length<n.exactLength.value;(l||c)&&(P(s,{code:l?j.too_big:j.too_small,minimum:c?n.exactLength.value:void 0,maximum:l?n.exactLength.value:void 0,type:"array",inclusive:!0,exact:!0,message:n.exactLength.message}),r.dirty())}if(n.minLength!==null&&s.data.length<n.minLength.value&&(P(s,{code:j.too_small,minimum:n.minLength.value,type:"array",inclusive:!0,exact:!1,message:n.minLength.message}),r.dirty()),n.maxLength!==null&&s.data.length>n.maxLength.value&&(P(s,{code:j.too_big,maximum:n.maxLength.value,type:"array",inclusive:!0,exact:!1,message:n.maxLength.message}),r.dirty()),s.common.async)return Promise.all([...s.data].map((l,c)=>n.type._parseAsync(new Ue(s,l,s.path,c)))).then(l=>ke.mergeArray(r,l));const i=[...s.data].map((l,c)=>n.type._parseSync(new Ue(s,l,s.path,c)));return ke.mergeArray(r,i)}get element(){return this._def.type}min(t,s){return new Ae({...this._def,minLength:{value:t,message:D.toString(s)}})}max(t,s){return new Ae({...this._def,maxLength:{value:t,message:D.toString(s)}})}length(t,s){return new Ae({...this._def,exactLength:{value:t,message:D.toString(s)}})}nonempty(t){return this.min(1,t)}}Ae.create=(a,t)=>new Ae({type:a,minLength:null,maxLength:null,exactLength:null,typeName:H.ZodArray,...J(t)});function Ye(a){if(a instanceof ue){const t={};for(const s in a.shape){const r=a.shape[s];t[s]=ze.create(Ye(r))}return new ue({...a._def,shape:()=>t})}else return a instanceof Ae?new Ae({...a._def,type:Ye(a.element)}):a instanceof ze?ze.create(Ye(a.unwrap())):a instanceof tt?tt.create(Ye(a.unwrap())):a instanceof Ze?Ze.create(a.items.map(t=>Ye(t))):a}class ue extends se{constructor(){super(...arguments),this._cached=null,this.nonstrict=this.passthrough,this.augment=this.extend}_getCached(){if(this._cached!==null)return this._cached;const t=this._def.shape(),s=ae.objectKeys(t);return this._cached={shape:t,keys:s},this._cached}_parse(t){if(this._getType(t)!==O.object){const x=this._getOrReturnCtx(t);return P(x,{code:j.invalid_type,expected:O.object,received:x.parsedType}),B}const{status:r,ctx:n}=this._processInputParams(t),{shape:i,keys:l}=this._getCached(),c=[];if(!(this._def.catchall instanceof Ve&&this._def.unknownKeys==="strip"))for(const x in n.data)l.includes(x)||c.push(x);const u=[];for(const x of l){const p=i[x],v=n.data[x];u.push({key:{status:"valid",value:x},value:p._parse(new Ue(n,v,n.path,x)),alwaysSet:x in n.data})}if(this._def.catchall instanceof Ve){const x=this._def.unknownKeys;if(x==="passthrough")for(const p of c)u.push({key:{status:"valid",value:p},value:{status:"valid",value:n.data[p]}});else if(x==="strict")c.length>0&&(P(n,{code:j.unrecognized_keys,keys:c}),r.dirty());else if(x!=="strip")throw new Error("Internal ZodObject error: invalid unknownKeys value.")}else{const x=this._def.catchall;for(const p of c){const v=n.data[p];u.push({key:{status:"valid",value:p},value:x._parse(new Ue(n,v,n.path,p)),alwaysSet:p in n.data})}}return n.common.async?Promise.resolve().then(async()=>{const x=[];for(const p of u){const v=await p.key,y=await p.value;x.push({key:v,value:y,alwaysSet:p.alwaysSet})}return x}).then(x=>ke.mergeObjectSync(r,x)):ke.mergeObjectSync(r,u)}get shape(){return this._def.shape()}strict(t){return D.errToObj,new ue({...this._def,unknownKeys:"strict",...t!==void 0?{errorMap:(s,r)=>{const n=this._def.errorMap?.(s,r).message??r.defaultError;return s.code==="unrecognized_keys"?{message:D.errToObj(t).message??n}:{message:n}}}:{}})}strip(){return new ue({...this._def,unknownKeys:"strip"})}passthrough(){return new ue({...this._def,unknownKeys:"passthrough"})}extend(t){return new ue({...this._def,shape:()=>({...this._def.shape(),...t})})}merge(t){return new ue({unknownKeys:t._def.unknownKeys,catchall:t._def.catchall,shape:()=>({...this._def.shape(),...t._def.shape()}),typeName:H.ZodObject})}setKey(t,s){return this.augment({[t]:s})}catchall(t){return new ue({...this._def,catchall:t})}pick(t){const s={};for(const r of ae.objectKeys(t))t[r]&&this.shape[r]&&(s[r]=this.shape[r]);return new ue({...this._def,shape:()=>s})}omit(t){const s={};for(const r of ae.objectKeys(this.shape))t[r]||(s[r]=this.shape[r]);return new ue({...this._def,shape:()=>s})}deepPartial(){return Ye(this)}partial(t){const s={};for(const r of ae.objectKeys(this.shape)){const n=this.shape[r];t&&!t[r]?s[r]=n:s[r]=n.optional()}return new ue({...this._def,shape:()=>s})}required(t){const s={};for(const r of ae.objectKeys(this.shape))if(t&&!t[r])s[r]=this.shape[r];else{let i=this.shape[r];for(;i instanceof ze;)i=i._def.innerType;s[r]=i}return new ue({...this._def,shape:()=>s})}keyof(){return bs(ae.objectKeys(this.shape))}}ue.create=(a,t)=>new ue({shape:()=>a,unknownKeys:"strip",catchall:Ve.create(),typeName:H.ZodObject,...J(t)});ue.strictCreate=(a,t)=>new ue({shape:()=>a,unknownKeys:"strict",catchall:Ve.create(),typeName:H.ZodObject,...J(t)});ue.lazycreate=(a,t)=>new ue({shape:a,unknownKeys:"strip",catchall:Ve.create(),typeName:H.ZodObject,...J(t)});class jt extends se{_parse(t){const{ctx:s}=this._processInputParams(t),r=this._def.options;function n(i){for(const c of i)if(c.result.status==="valid")return c.result;for(const c of i)if(c.result.status==="dirty")return s.common.issues.push(...c.ctx.common.issues),c.result;const l=i.map(c=>new Oe(c.ctx.common.issues));return P(s,{code:j.invalid_union,unionErrors:l}),B}if(s.common.async)return Promise.all(r.map(async i=>{const l={...s,common:{...s.common,issues:[]},parent:null};return{result:await i._parseAsync({data:s.data,path:s.path,parent:l}),ctx:l}})).then(n);{let i;const l=[];for(const u of r){const x={...s,common:{...s.common,issues:[]},parent:null},p=u._parseSync({data:s.data,path:s.path,parent:x});if(p.status==="valid")return p;p.status==="dirty"&&!i&&(i={result:p,ctx:x}),x.common.issues.length&&l.push(x.common.issues)}if(i)return s.common.issues.push(...i.ctx.common.issues),i.result;const c=l.map(u=>new Oe(u));return P(s,{code:j.invalid_union,unionErrors:c}),B}}get options(){return this._def.options}}jt.create=(a,t)=>new jt({options:a,typeName:H.ZodUnion,...J(t)});function Dt(a,t){const s=De(a),r=De(t);if(a===t)return{valid:!0,data:a};if(s===O.object&&r===O.object){const n=ae.objectKeys(t),i=ae.objectKeys(a).filter(c=>n.indexOf(c)!==-1),l={...a,...t};for(const c of i){const u=Dt(a[c],t[c]);if(!u.valid)return{valid:!1};l[c]=u.data}return{valid:!0,data:l}}else if(s===O.array&&r===O.array){if(a.length!==t.length)return{valid:!1};const n=[];for(let i=0;i<a.length;i++){const l=a[i],c=t[i],u=Dt(l,c);if(!u.valid)return{valid:!1};n.push(u.data)}return{valid:!0,data:n}}else return s===O.date&&r===O.date&&+a==+t?{valid:!0,data:a}:{valid:!1}}class Nt extends se{_parse(t){const{status:s,ctx:r}=this._processInputParams(t),n=(i,l)=>{if(Qt(i)||Qt(l))return B;const c=Dt(i.value,l.value);return c.valid?((Kt(i)||Kt(l))&&s.dirty(),{status:s.value,value:c.data}):(P(r,{code:j.invalid_intersection_types}),B)};return r.common.async?Promise.all([this._def.left._parseAsync({data:r.data,path:r.path,parent:r}),this._def.right._parseAsync({data:r.data,path:r.path,parent:r})]).then(([i,l])=>n(i,l)):n(this._def.left._parseSync({data:r.data,path:r.path,parent:r}),this._def.right._parseSync({data:r.data,path:r.path,parent:r}))}}Nt.create=(a,t,s)=>new Nt({left:a,right:t,typeName:H.ZodIntersection,...J(s)});class Ze extends se{_parse(t){const{status:s,ctx:r}=this._processInputParams(t);if(r.parsedType!==O.array)return P(r,{code:j.invalid_type,expected:O.array,received:r.parsedType}),B;if(r.data.length<this._def.items.length)return P(r,{code:j.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),B;!this._def.rest&&r.data.length>this._def.items.length&&(P(r,{code:j.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),s.dirty());const i=[...r.data].map((l,c)=>{const u=this._def.items[c]||this._def.rest;return u?u._parse(new Ue(r,l,r.path,c)):null}).filter(l=>!!l);return r.common.async?Promise.all(i).then(l=>ke.mergeArray(s,l)):ke.mergeArray(s,i)}get items(){return this._def.items}rest(t){return new Ze({...this._def,rest:t})}}Ze.create=(a,t)=>{if(!Array.isArray(a))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new Ze({items:a,typeName:H.ZodTuple,rest:null,...J(t)})};class os extends se{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(t){const{status:s,ctx:r}=this._processInputParams(t);if(r.parsedType!==O.map)return P(r,{code:j.invalid_type,expected:O.map,received:r.parsedType}),B;const n=this._def.keyType,i=this._def.valueType,l=[...r.data.entries()].map(([c,u],x)=>({key:n._parse(new Ue(r,c,r.path,[x,"key"])),value:i._parse(new Ue(r,u,r.path,[x,"value"]))}));if(r.common.async){const c=new Map;return Promise.resolve().then(async()=>{for(const u of l){const x=await u.key,p=await u.value;if(x.status==="aborted"||p.status==="aborted")return B;(x.status==="dirty"||p.status==="dirty")&&s.dirty(),c.set(x.value,p.value)}return{status:s.value,value:c}})}else{const c=new Map;for(const u of l){const x=u.key,p=u.value;if(x.status==="aborted"||p.status==="aborted")return B;(x.status==="dirty"||p.status==="dirty")&&s.dirty(),c.set(x.value,p.value)}return{status:s.value,value:c}}}}os.create=(a,t,s)=>new os({valueType:t,keyType:a,typeName:H.ZodMap,...J(s)});class ut extends se{_parse(t){const{status:s,ctx:r}=this._processInputParams(t);if(r.parsedType!==O.set)return P(r,{code:j.invalid_type,expected:O.set,received:r.parsedType}),B;const n=this._def;n.minSize!==null&&r.data.size<n.minSize.value&&(P(r,{code:j.too_small,minimum:n.minSize.value,type:"set",inclusive:!0,exact:!1,message:n.minSize.message}),s.dirty()),n.maxSize!==null&&r.data.size>n.maxSize.value&&(P(r,{code:j.too_big,maximum:n.maxSize.value,type:"set",inclusive:!0,exact:!1,message:n.maxSize.message}),s.dirty());const i=this._def.valueType;function l(u){const x=new Set;for(const p of u){if(p.status==="aborted")return B;p.status==="dirty"&&s.dirty(),x.add(p.value)}return{status:s.value,value:x}}const c=[...r.data.values()].map((u,x)=>i._parse(new Ue(r,u,r.path,x)));return r.common.async?Promise.all(c).then(u=>l(u)):l(c)}min(t,s){return new ut({...this._def,minSize:{value:t,message:D.toString(s)}})}max(t,s){return new ut({...this._def,maxSize:{value:t,message:D.toString(s)}})}size(t,s){return this.min(t,s).max(t,s)}nonempty(t){return this.min(1,t)}}ut.create=(a,t)=>new ut({valueType:a,minSize:null,maxSize:null,typeName:H.ZodSet,...J(t)});class ls extends se{get schema(){return this._def.getter()}_parse(t){const{ctx:s}=this._processInputParams(t);return this._def.getter()._parse({data:s.data,path:s.path,parent:s})}}ls.create=(a,t)=>new ls({getter:a,typeName:H.ZodLazy,...J(t)});class ds extends se{_parse(t){if(t.data!==this._def.value){const s=this._getOrReturnCtx(t);return P(s,{received:s.data,code:j.invalid_literal,expected:this._def.value}),B}return{status:"valid",value:t.data}}get value(){return this._def.value}}ds.create=(a,t)=>new ds({value:a,typeName:H.ZodLiteral,...J(t)});function bs(a,t){return new Xe({values:a,typeName:H.ZodEnum,...J(t)})}class Xe extends se{_parse(t){if(typeof t.data!="string"){const s=this._getOrReturnCtx(t),r=this._def.values;return P(s,{expected:ae.joinValues(r),received:s.parsedType,code:j.invalid_type}),B}if(this._cache||(this._cache=new Set(this._def.values)),!this._cache.has(t.data)){const s=this._getOrReturnCtx(t),r=this._def.values;return P(s,{received:s.data,code:j.invalid_enum_value,options:r}),B}return Te(t.data)}get options(){return this._def.values}get enum(){const t={};for(const s of this._def.values)t[s]=s;return t}get Values(){const t={};for(const s of this._def.values)t[s]=s;return t}get Enum(){const t={};for(const s of this._def.values)t[s]=s;return t}extract(t,s=this._def){return Xe.create(t,{...this._def,...s})}exclude(t,s=this._def){return Xe.create(this.options.filter(r=>!t.includes(r)),{...this._def,...s})}}Xe.create=bs;class cs extends se{_parse(t){const s=ae.getValidEnumValues(this._def.values),r=this._getOrReturnCtx(t);if(r.parsedType!==O.string&&r.parsedType!==O.number){const n=ae.objectValues(s);return P(r,{expected:ae.joinValues(n),received:r.parsedType,code:j.invalid_type}),B}if(this._cache||(this._cache=new Set(ae.getValidEnumValues(this._def.values))),!this._cache.has(t.data)){const n=ae.objectValues(s);return P(r,{received:r.data,code:j.invalid_enum_value,options:n}),B}return Te(t.data)}get enum(){return this._def.values}}cs.create=(a,t)=>new cs({values:a,typeName:H.ZodNativeEnum,...J(t)});class wt extends se{unwrap(){return this._def.type}_parse(t){const{ctx:s}=this._processInputParams(t);if(s.parsedType!==O.promise&&s.common.async===!1)return P(s,{code:j.invalid_type,expected:O.promise,received:s.parsedType}),B;
vendor: 5,153 bytes, line 2
2const r=s.parsedType===O.promise?s.data:Promise.resolve(s.data);return Te(r.then(n=>this._def.type.parseAsync(n,{path:s.path,errorMap:s.common.contextualErrorMap})))}}wt.create=(a,t)=>new wt({type:a,typeName:H.ZodPromise,...J(t)});class et extends se{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===H.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(t){const{status:s,ctx:r}=this._processInputParams(t),n=this._def.effect||null,i={addIssue:l=>{P(r,l),l.fatal?s.abort():s.dirty()},get path(){return r.path}};if(i.addIssue=i.addIssue.bind(i),n.type==="preprocess"){const l=n.transform(r.data,i);if(r.common.async)return Promise.resolve(l).then(async c=>{if(s.value==="aborted")return B;const u=await this._def.schema._parseAsync({data:c,path:r.path,parent:r});return u.status==="aborted"?B:u.status==="dirty"||s.value==="dirty"?dt(u.value):u});{if(s.value==="aborted")return B;const c=this._def.schema._parseSync({data:l,path:r.path,parent:r});return c.status==="aborted"?B:c.status==="dirty"||s.value==="dirty"?dt(c.value):c}}if(n.type==="refinement"){const l=c=>{const u=n.refinement(c,i);if(r.common.async)return Promise.resolve(u);if(u instanceof Promise)throw new Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");return c};if(r.common.async===!1){const c=this._def.schema._parseSync({data:r.data,path:r.path,parent:r});return c.status==="aborted"?B:(c.status==="dirty"&&s.dirty(),l(c.value),{status:s.value,value:c.value})}else return this._def.schema._parseAsync({data:r.data,path:r.path,parent:r}).then(c=>c.status==="aborted"?B:(c.status==="dirty"&&s.dirty(),l(c.value).then(()=>({status:s.value,value:c.value}))))}if(n.type==="transform")if(r.common.async===!1){const l=this._def.schema._parseSync({data:r.data,path:r.path,parent:r});if(!Qe(l))return B;const c=n.transform(l.value,i);if(c instanceof Promise)throw new Error("Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.");return{status:s.value,value:c}}else return this._def.schema._parseAsync({data:r.data,path:r.path,parent:r}).then(l=>Qe(l)?Promise.resolve(n.transform(l.value,i)).then(c=>({status:s.value,value:c})):B);ae.assertNever(n)}}et.create=(a,t,s)=>new et({schema:a,typeName:H.ZodEffects,effect:t,...J(s)});et.createWithPreprocess=(a,t,s)=>new et({schema:t,effect:{type:"preprocess",transform:a},typeName:H.ZodEffects,...J(s)});class ze extends se{_parse(t){return this._getType(t)===O.undefined?Te(void 0):this._def.innerType._parse(t)}unwrap(){return this._def.innerType}}ze.create=(a,t)=>new ze({innerType:a,typeName:H.ZodOptional,...J(t)});class tt extends se{_parse(t){return this._getType(t)===O.null?Te(null):this._def.innerType._parse(t)}unwrap(){return this._def.innerType}}tt.create=(a,t)=>new tt({innerType:a,typeName:H.ZodNullable,...J(t)});class Mt extends se{_parse(t){const{ctx:s}=this._processInputParams(t);let r=s.data;return s.parsedType===O.undefined&&(r=this._def.defaultValue()),this._def.innerType._parse({data:r,path:s.path,parent:s})}removeDefault(){return this._def.innerType}}Mt.create=(a,t)=>new Mt({innerType:a,typeName:H.ZodDefault,defaultValue:typeof t.default=="function"?t.default:()=>t.default,...J(t)});class $t extends se{_parse(t){const{ctx:s}=this._processInputParams(t),r={...s,common:{...s.common,issues:[]}},n=this._def.innerType._parse({data:r.data,path:r.path,parent:{...r}});return bt(n)?n.then(i=>({status:"valid",value:i.status==="valid"?i.value:this._def.catchValue({get error(){return new Oe(r.common.issues)},input:r.data})})):{status:"valid",value:n.status==="valid"?n.value:this._def.catchValue({get error(){return new Oe(r.common.issues)},input:r.data})}}removeCatch(){return this._def.innerType}}$t.create=(a,t)=>new $t({innerType:a,typeName:H.ZodCatch,catchValue:typeof t.catch=="function"?t.catch:()=>t.catch,...J(t)});class us extends se{_parse(t){if(this._getType(t)!==O.nan){const r=this._getOrReturnCtx(t);return P(r,{code:j.invalid_type,expected:O.nan,received:r.parsedType}),B}return{status:"valid",value:t.data}}}us.create=a=>new us({typeName:H.ZodNaN,...J(a)});class rr extends se{_parse(t){const{ctx:s}=this._processInputParams(t),r=s.data;return this._def.type._parse({data:r,path:s.path,parent:s})}unwrap(){return this._def.type}}class Ut extends se{_parse(t){const{status:s,ctx:r}=this._processInputParams(t);if(r.common.async)return(async()=>{const i=await this._def.in._parseAsync({data:r.data,path:r.path,parent:r});return i.status==="aborted"?B:i.status==="dirty"?(s.dirty(),dt(i.value)):this._def.out._parseAsync({data:i.value,path:r.path,parent:r})})();{const n=this._def.in._parseSync({data:r.data,path:r.path,parent:r});return n.status==="aborted"?B:n.status==="dirty"?(s.dirty(),{status:"dirty",value:n.value}):this._def.out._parseSync({data:n.value,path:r.path,parent:r})}}static create(t,s){return new Ut({in:t,out:s,typeName:H.ZodPipeline})}}class zt extends se{_parse(t){const s=this._def.innerType._parse(t),r=n=>(Qe(n)&&(n.value=Object.freeze(n.value)),n);return bt(s)?s.then(n=>r(n)):r(s)}unwrap(){return this._def.innerType}}zt.create=(a,t)=>
2new zt({innerType:a,typeName:H.ZodReadonly,...J(t)});var H;(function(a){a.ZodString="ZodString",a.ZodNumber="ZodNumber",a.ZodNaN="ZodNaN",a.ZodBigInt="ZodBigInt",a.ZodBoolean="ZodBoolean",a.ZodDate="ZodDate",a.ZodSymbol="ZodSymbol",a.ZodUndefined="ZodUndefined",a.ZodNull="ZodNull",a.ZodAny="ZodAny",a.ZodUnknown="ZodUnknown",a.ZodNever="ZodNever",a.ZodVoid="ZodVoid",a.ZodArray="ZodArray",a.ZodObject="ZodObject",a.ZodUnion="ZodUnion",a.ZodDiscriminatedUnion="ZodDiscriminatedUnion",a.ZodIntersection="ZodIntersection",a.ZodTuple="ZodTuple",a.ZodRecord="ZodRecord",a.ZodMap="ZodMap",a.ZodSet="ZodSet",a.ZodFunction="ZodFunction",a.ZodLazy="ZodLazy",a.ZodLiteral="ZodLiteral",a.ZodEnum="ZodEnum",a.ZodEffects="ZodEffects",a.ZodNativeEnum="ZodNativeEnum",a.ZodOptional="ZodOptional",a.ZodNullable="ZodNullable",a.ZodDefault="ZodDefault",a.ZodCatch="ZodCatch",a.ZodPromise="ZodPromise",a.ZodBranded="ZodBranded",a.ZodPipeline="ZodPipeline",a.ZodReadonly="ZodReadonly"})(H||(H={}));const Ie=$e.create,ms=Ke.create;Ve.create;const hs=Ae.create,nr=ue.create;jt.create;Nt.create;Ze.create;const Rt=Xe.create;wt.create;ze.create;tt.create;nr({teacherId:Ie().uuid("teacherId must be a valid UUID").min(1,"teacherId is required"),studentIds:hs(Ie().uuid("Each studentId must be a valid UUID")).min(1,"At least one student is required"),instrument:Ie().min(1,"Instrument is required").max(100,"Instrument name too long"),lessonType:Rt(["solo","extended","band"],{errorMap:()=>({message:'lessonType must be "solo", "extended", or "band"'})}).default("solo"),durationMinutes:ms().int("durationMinutes must be an integer").min(15,"Duration must be at least 15 minutes").max(180,"Duration cannot exceed 180 minutes"),startDate:Ie().regex(/^\d{4}-\d{2}-\d{2}$/,"startDate must be in YYYY-MM-DD format"),startTime:Ie().regex(/^\d{2}:\d{2}$/,"startTime must be in HH:MM format"),timezone:Ie().default("Europe/London"),recurrenceFreq:Rt(["DAILY","WEEKLY","BIWEEKLY","MONTHLY","YEARLY"]).optional().nullable(),recurrenceInterval:ms().int().min(1,"recurrenceInterval must be at least 1").default(1),recurrenceByDay:hs(Rt(["SU","MO","TU","WE","TH","FR","SA"])).optional().nullable(),recurrenceUntil:Ie().regex(/^\d{4}-\d{2}-\d{2}$/,"recurrenceUntil must be in YYYY-MM-DD format").optional().nullable(),notes:Ie().max(500,"Notes cannot exceed 500 characters").optional().nullable(),createdBy:Ie().uuid("createdBy must be a valid UUID").optional().nullable()});async function ot(){try{const{apiFetch:a}=await Y(async()=>{const{apiFetch:s}=await import("./api-CyvozDRd.js");return{apiFetch:s}},[]),t=await a("/api/admin/teachers");return!t||!Array.isArray(t)?[]:(t||[]).map(s=>({id:s.user_id,name:s.name,email:s.email,phone:s.phone,years:s.years,about:s.about,image:s.image,instruments:Array.isArray(s.instruments)?s.instruments:typeof s.instruments=="string"?JSON.parse(s.instruments):[]}))}catch(a){return console.error(a),[]}}function Mr(){const[a,t]=m.useState([]),[s,r]=m.useState([]),[n,i]=m.useState(!1),[l,c]=m.useState({}),[u,x]=m.useState(null),[p,v]=m.useState(!1),[y,I]=m.useState("Piano"),[U,V]=m.useState({basic:!0,contact:!0,about:!1,media:!1}),L=Vs(),[G,W]=m.useState(!1),[ne,E]=m.useState(!1),[d,C]=m.useState(""),[k,b]=m.useState(""),[F,T]=m.useState(!1),[R,M]=m.useState([]),[A,te]=m.useState(!1),{toast:S}=Pe(),N=async()=>{if(!d||!k){S({title:"Missing fields",description:"Subject and message are required"});return}try{const{apiFetch:f}=await Y(async()=>{const{apiFetch:re}=await import("./api-CyvozDRd.js");return{apiFetch:re}},[]);if(!(await f("/api/admin/newsletters",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({subject:d,html:k,plain:k.replace(/<[^>]+>/g,"")})})).ok)throw new Error("Failed to send newsletter");S({title:"Sent",description:"Newsletter queued/sent"}),C(""),b(""),E(!1)}catch(f){console.error(f),S({title:"Error",description:f?.message||"Unable to send"})}},oe=async()=>{te(!0);try{const{apiFetch:f}=await Y(async()=>{const{apiFetch:re}=await import("./api-CyvozDRd.js");return{apiFetch:re}},[]),_=await f("/api/admin/newsletters/subscribers");console.log("ð§ Subscribers received from API:",_),console.log("ð§ Is array?",Array.isArray(_)),console.log("ð§ Length:",_?.length),M(Array.isArray(_)?_:[])}catch(f){console.error("â Fetch subscribers error:",f),S({title:"Error",description:f?.message||"Failed to load subscribers"})}finally{te(!1)}},_e=async(f,_)=>{try{const{apiFetch:re}=await Y(async()=>{const{apiFetch:Fe}=await import("./api-CyvozDRd.js");return{apiFetch:Fe}},[]);if(!(await re(`/api/admin/newsletters/subscribers/${f}`,{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify({subscribed:!_})})).ok)throw new Error("Failed to update subscription");S({title:"Success",description:_?"User unsubscribed":"User subscribed"}),oe()}catch(re){console.error(re),S({title:"Error",description:re?.message||"Failed to update subscription"})}};m.useEffect(()=>{localStorage.getItem("inTuneAdmin")||L("/admin/login"),(async()=>{try{const{ensureCsrfToken:_}=await Y(async()=>{const{ensureCsrfToken:je}=await import("./api-CyvozDRd.js");return{ensureCsrfToken:je}},[]);await _()||console.warn("â ï¸ Failed to initialize CSRF token - some operations may fail")}catch(_){console.error("â Error initializing CSRF token:",_)}try{const _=await ot();t(_)}catch(_){console.error("Failed to load teachers:",_),t([])}try{const _=await Je.list();r(_)}catch(_){console.error("Failed to load students:",_),r([])}})()},[L]);const ve=async f=>{f.preventDefault();try{if(u){const je=!!l.password,{apiFetch:Fe}=await Y(async()=>{const{apiFetch:Be}=await import("./api-CyvozDRd.js");return{apiFetch:Be}},[]),qe=await Fe("/api/admin/teachers",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({userId:u,email:l.email,name:l.name,phone:l.phone,years:l.years,about:l.about,image:l.image,password:l.password||void 0,phonePublic:l.phonePublic||!1,emailPublic:l.emailPublic||!1,instruments:l.instruments||[]})});if(!qe.ok)throw new Error(`Failed to update teacher: ${qe.statusText}`);c({}),x(null),v(!1),V({basic:!0,contact:!0,about:!1,media:!1});const st=await ot();t(st),S(je?{title:"Teacher updated",description:"Password changed successfully. The user can now login with the new password."}:{title:"Teacher updated"});return}const{apiFetch:_}=await Y(async()=>{const{apiFetch:je}=await import("./api-CyvozDRd.js");return{apiFetch:je}},[]);await _("/api/admin/teachers",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({email:l.email,name:l.name,phone:l.phone,years:l.years,about:l.about,image:l.image,password:l.password||void 0,phonePublic:l.phonePublic||!1,emailPublic:l.emailPublic||!1,instruments:l.instruments||[]})}),c({}),v(!1),V({basic:!0,contact:!0,about:!1,media:!1});const re=await ot();t(re)}catch(_){console.error(_),alert("Unable to save teacher")}},le=async f=>{if(confirm("Are you sure you want to remove this teacher? This action cannot be undone."))try{console.log("ðï¸ Attempting to delete teacher with ID:",f);const{apiFetch:_}=await Y(async()=>{const{apiFetch:Fe}=await import("./api-CyvozDRd.js");return{apiFetch:Fe}},[]),re=await _(`/api/admin/teachers/${f}`,{method:"DELETE"});console.log("â
Delete response:",re);const je=await ot();console.log("ð Refreshed teachers list:",je.length,"teachers"),t(je),S({title:"Teacher removed",description:"The teacher has been successfully deleted."})}catch(_){console.error("â Error removing teacher:",_),S({title:"Error",description:"Unable to remove teacher",variant:"destructive"})}},ce=f=>{x(f.id),c({...f}),V({basic:!0,contact:!0,about:!1,media:!1}),v(!0)}
2,pe=()=>{const f=l.instruments||[];if(f.length>=5)return alert("Max 5 instruments");f.includes(y)||c(_=>({..._,instruments:[..._.instruments||[],y]}))},Ne=f=>c(_=>({..._,instruments:(_.instruments||[]).filter(re=>re!==f)})),be=async()=>{i(!0);const f=await Ps("music teacher portrait");i(!1),c(_=>({..._,image:f}))},ye=f=>{const _=new FileReader;_.onload=()=>c(re=>({...re,image:_.result})),_.readAsDataURL(f)},Ce=f=>{f.preventDefault(),f.dataTransfer.files&&f.dataTransfer.files[0]&&ye(f.dataTransfer.files[0])},xe=f=>{const _=f.target.files&&f.target.files[0];_&&ye(_)},he=async()=>{console.log(` 3ââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââ`),console.log("ðª [LOGOUT] CLIENT-SIDE LOGOUT PROCESS STARTED"),console.log(`ââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââ 4`);try{console.log("ð¡ [LOGOUT] Sending logout request to server...");const{apiFetch:f}=await Y(async()=>{const{apiFetch:re}=await import("./api-CyvozDRd.js");return{apiFetch:re}},[]),_=await f("/api/auth/logout",{method:"POST",credentials:"include"});_.ok?console.log("â [LOGOUT] Server logout successful"):console.warn("â ï¸ [LOGOUT] Server logout returned status:",_.status)}catch(f){console.error("â [LOGOUT] Server logout request failed:",f)}try{if(console.log(` 5ð§¹ [LOGOUT] Starting client-side cleanup...`),console.log(" ð¦ Clearing InTune auth storage..."),Es(),console.log(" ð¦ Clearing session storage..."),sessionStorage.clear(),typeof window<"u"&&window.caches){console.log(" ð¾ Clearing cache storage...");const f=await window.caches.keys();await Promise.all(f.map(_=>window.caches.delete(_))),console.log(` â Cleared ${f.length} cache(s)`)}if(typeof document<"u"){console.log(" ðª Clearing document cookies...");const f=document.cookie.split(";").length;document.cookie.split(";").forEach(_=>{const re=_.indexOf("="),je=re>-1?_.substr(0,re).trim():_.trim();document.cookie=`${je}=;expires=Thu, 01 Jan 1970 00:00:00 GMT;path=/`}),console.log(` â Cleared ${f} cookie(s)`)}if(typeof navigator<"u"&&navigator.serviceWorker&&navigator.serviceWorker.getRegistrations){console.log(" ð§ Unregistering service workers...");const f=await navigator.serviceWorker.getRegistrations();await Promise.all(f.map(_=>_.unregister())),console.log(` â Unregistered ${f.length} service worker(s)`)}console.log(` 6â [LOGOUT] Client-side cleanup complete`)}catch(f){console.error(` 7â [LOGOUT] Error during client cleanup:`,f)}console.log(` 8ð [LOGOUT] Navigating to home page...`),console.log(`ââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââ 9`),L("/")},[$,Q]=m.useState("teachers");return m.useEffect(()=>{console.log("ð¯ FRONTEND BUILD: 2026-02-16-CSRF-FIX")},[]),e.jsxs("div",{className:"container mx-auto py-12",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("h1",{className:"text-2xl font-bold",children:"Admin page"}),e.jsxs("div",{className:"flex gap-2 flex-wrap",children:[e.jsx(Us,{}),e.jsx("button",{onClick:he,className:"px-3 py-2 rounded-md border",children:"Logout"})]})]}),e.jsxs("div",{className:"mt-6",children:[e.jsxs("div",{role:"tablist","aria-label":"Admin sections",className:"flex gap-2 flex-wrap",children:[e.jsx("button",{onClick:()=>Q("teachers"),role:"tab","aria-selected":$==="teachers",className:`px-4 py-2 rounded-md ${$==="teachers"?"bg-card shadow":"bg-muted"} text-foreground`,children:"Teachers"}),e.jsx("button",{onClick:()=>Q("site"),role:"tab","aria-selected":$==="site",className:`px-4 py-2 rounded-md ${$==="site"?"bg-card shadow":"bg-muted"} text-foreground`,children:e.jsx("p",{children:"Newsletter&More"})}),e.jsx("button",{onClick:()=>Q("schedule"),role:"tab","aria-selected":$==="schedule",className:`px-4 py-2 rounded-md ${$==="schedule"?"bg-card shadow":"bg-muted"} text-foreground`,children:"Schedule"}),e.jsx("button",{onClick:()=>Q("theme"),role:"tab","aria-selected":$==="theme",className:`px-4 py-2 rounded-md ${$==="theme"?"bg-card shadow":"bg-muted"} text-foreground`,children:"Theme"}),e.jsx("button",{onClick:()=>Q("students"),role:"tab","aria-selected":$==="students",className:`px-4 py-2 rounded-md ${$==="students"?"bg-card shadow":"bg-muted"} text-foreground`,children:"Students"}),e.jsx("button",{onClick:()=>Q("assignments"),role:"tab","aria-selected":$==="assignments",className:`px-4 py-2 rounded-md ${$==="assignments"?"bg-card shadow":"bg-muted"} text-foreground`,children:"Assignments"}),e.jsx("button",{onClick:()=>Q("intake"),role:"tab","aria-selected":$==="intake",className:`px-4 py-2 rounded-md ${$==="intake"?"bg-card shadow":"bg-muted"} text-foreground`,children:"Intake Approval"}),e.jsx("button",{onClick:()=>Q("reports"),role:"tab","aria-selected":$==="reports",className:`px-4 py-2 rounded-md ${$==="reports"?"bg-card shadow":"bg-muted"} text-foreground`,children:"Reports"}),e.jsx("button",{onClick:()=>Q("discussion"),role:"tab","aria-selected":$==="discussion",className:`px-4 py-2 rounded-md ${$==="discussion"?"bg-card shadow":"bg-muted"} text-foreground`,children:"Discussion"}),e.jsx("button",{onClick:()=>Q("forums"),role:"tab","aria-selected":$==="forums",className:`px-4 py-2 rounded-md ${$==="forums"?"bg-card shadow":"bg-muted"} text-foreground`,children:"Forums"}),e.jsx("button",{onClick:()=>Q("chats"),role:"tab","aria-selected":$==="chats",className:`px-4 py-2 rounded-md ${$==="chats"?"bg-card shadow":"bg-muted"} text-foreground`,children:"Chats"}),e.jsx("button",{onClick:()=>Q("security"),role:"tab","aria-selected":$==="security",className:`px-4 py-2 rounded-md ${$==="security"?"bg-card shadow":"bg-muted"} text-foreground`,children:"Security"}),e.jsx("button",{onClick:()=>Q("profile"),role:"tab","aria-selected":$==="profile",className:`px-4 py-2 rounded-md ${$==="profile"?"bg-card shadow":"bg-muted"} text-foreground`,children:"My Profile"}),e.jsx("button",{onClick:()=>Q("social"),role:"tab","aria-selected":$==="social",className:`px-4 py-2 rounded-md ${$==="social"?"bg-card shadow":"bg-muted"} text-foreground`,children:"Social Media"}),e.jsx("button",{onClick:()=>Q("blog"),role:"tab","aria-selected":$==="blog",className:`px-4 py-2 rounded-md ${$==="blog"?"bg-card shadow":"bg-muted"} text-foreground`,children:"Blog"}),e.jsx("button",{onClick:()=>Q("faq"),role:"tab","aria-selected":$==="faq",className:`px-4 py-2 rounded-md ${$==="faq"?"bg-card shadow":"bg-muted"} text-foreground`,children:"FAQ"}),e.jsx("button",{onClick:()=>L("/admin/qr-codes"),role:"tab",className:"px-4 py-2 rounded-md bg-muted text-foreground hover:bg-card hover:shadow transition-all",children:"QR Codes"})]}),e.jsxs("div",{className:"mt-6",children:[$==="teachers"&&e.jsxs("div",{className:"grid md:grid-cols-3 gap-6",children:[e.jsxs("div",{className:"md:col-span-1 rounded-lg border p-4",children:[e.jsx("h2",{className:"font-semibold",children:"Teachers"}
9),e.jsx("p",{className:"text-sm text-foreground/70 mt-1",children:"Add or edit teachers. Click the button to open the form."}),e.jsx("div",{className:"mt-3",children:e.jsx(w,{onClick:()=>{c({}),x(null),v(!0)},variant:"gradient",children:"Add teacher"})}),e.jsx("div",{className:"mt-4 text-sm text-foreground/70",children:"You can also edit an existing teacher from the list to the right."})]}),e.jsxs("div",{className:"md:col-span-2",children:[e.jsx("h2",{className:"font-semibold",children:"Existing teachers"}),e.jsxs("div",{className:"mt-4 grid sm:grid-cols-2 gap-4",children:[a.length===0&&e.jsx("div",{className:"text-foreground/70",children:"No teachers yet. Use the button to add one."}),a.map(f=>e.jsx(or,{t:f,onEdit:()=>ce(f),onRemove:()=>le(f.id)},f.id))]})]})]}),$==="site"&&e.jsxs("div",{className:"rounded-lg border p-4",children:[e.jsx("h2",{className:"font-semibold",children:"Newsletter & more"}),e.jsxs("div",{className:"mt-4",children:[e.jsxs("div",{className:"flex gap-2 flex-wrap",children:[e.jsx(w,{onClick:()=>W(!0),className:"px-4 py-2",variant:"gradient",children:"Compose newsletter"}),e.jsx(w,{onClick:()=>E(f=>!f),className:"px-4 py-2",variant:"outline",children:ne?"Hide quick send":"Quick send"}),e.jsx(w,{onClick:()=>{T(!0),oe()},className:"px-4 py-2",variant:"ghost",children:"Manage subscribers"})]}),ne&&e.jsxs("div",{className:"mt-4 grid gap-2",children:[e.jsx("input",{value:d,onChange:f=>C(f.target.value),placeholder:"Subject",className:"h-10 rounded-md border px-3"}),e.jsx("textarea",{value:k,onChange:f=>b(f.target.value),placeholder:"Message (HTML allowed)",className:"rounded-md border px-3 py-2 min-h-[120px]"}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(w,{onClick:N,variant:"gradient",size:"lg",children:"Send to subscribers"}),e.jsx(w,{onClick:()=>{C(""),b("")},variant:"outline",children:"Clear"})]})]}),e.jsx("p",{className:"text-sm text-foreground/70 mt-3",children:"Use Compose for rich newsletters, Quick send for short announcements."})]})]}),$==="theme"&&e.jsxs("div",{className:"rounded-lg border p-4",children:[e.jsx("h2",{className:"font-semibold",children:"Theme"}),e.jsx("div",{className:"mt-4",children:e.jsx(lr,{})})]}),$==="students"&&e.jsxs("div",{className:"rounded-lg border p-4",children:[e.jsx("h2",{className:"font-semibold",children:"Students"}),e.jsx("div",{className:"mt-4",children:e.jsx(pr,{})})]}),$==="assignments"&&e.jsxs("div",{className:"rounded-lg border p-4",children:[e.jsx("h2",{className:"font-semibold",children:"Teacher-Student Assignments"}),e.jsx("div",{className:"mt-4",children:e.jsx(xr,{teachers:a,students:s})})]}),$==="intake"&&e.jsxs("div",{className:"rounded-lg border p-4",children:[e.jsx("h2",{className:"font-semibold",children:"Student Intake Approval"}),e.jsx("div",{className:"mt-4",children:e.jsx(Pa,{})})]}),$==="reports"&&e.jsxs("div",{className:"rounded-lg border p-4",children:[e.jsx("h2",{className:"font-semibold",children:"Reports"}),e.jsx("div",{className:"mt-4 grid gap-4",children:e.jsx(dr,{})})]}),$==="discussion"&&e.jsxs("div",{className:"rounded-lg border p-4",children:[e.jsx("h2",{className:"font-semibold",children:"Discussion"}),e.jsx("div",{className:"mt-4",children:e.jsx($s,{})})]}),$==="forums"&&e.jsx("div",{className:"rounded-lg border p-4",children:e.jsx("div",{className:"mt-4",children:e.jsx(Aa,{})})}),$==="chats"&&e.jsxs("div",{className:"rounded-lg border p-4",children:[e.jsx("h2",{className:"font-semibold",children:"Chats"}),e.jsx("div",{className:"mt-4",children:e.jsx(zs,{})})]}),$==="security"&&e.jsxs("div",{className:"rounded-lg border p-4",children:[e.jsx("h2",{className:"font-semibold",children:"Security"}),e.jsx("div",{className:"mt-4",children:e.jsx(Ca,{})})]}),$==="profile"&&e.jsxs("div",{className:"rounded-lg border p-4",children:[e.jsx("h2",{className:"font-semibold mb-4",children:"My Profile"}),e.jsx(Sa,{})]}),$==="social"&&e.jsx("div",{className:"rounded-lg border p-4",children:e.jsx(Fa,{})}),$==="blog"&&e.jsx("div",{className:"rounded-lg border p-4",children:e.jsx(Yt,{type:"blog"})}),$==="faq"&&e.jsx("div",{className:"rounded-lg border p-4",children:e.jsx(Yt,{type:"faq"})}),$==="schedule"&&e.jsxs("div",{className:"rounded-lg border p-4",children:[e.jsx("h2",{className:"font-semibold mb-4",children:"Schedule & Availability"}
9),e.jsx("p",{className:"text-sm text-foreground/70 mb-4",children:"Manage your working hours, view upcoming lessons, and approve trial booking requests from the home page."}),e.jsx("div",{className:"mt-4",children:e.jsx(Ta,{})})]})]})]}),G&&e.jsx("div",{className:"fixed inset-0 bg-black/40 flex items-center justify-center z-50",onMouseDown:f=>{f.target===f.currentTarget&&W(!1)},children:e.jsx("div",{className:"w-full max-w-3xl p-4",children:e.jsx(Ea,{onClose:()=>W(!1)})})}),F&&e.jsx("div",{className:"fixed inset-0 bg-black/40 flex items-center justify-center z-50",onMouseDown:f=>{f.target===f.currentTarget&&T(!1)},children:e.jsxs("div",{className:"bg-card rounded-lg p-6 max-w-2xl w-full max-h-[80vh] flex flex-col",children:[e.jsxs("div",{className:"flex items-center justify-between mb-4 flex-shrink-0",children:[e.jsx("h3",{className:"text-lg font-semibold",children:"Newsletter Subscribers"}),e.jsx(w,{variant:"ghost",size:"sm",onClick:()=>T(!1),children:"â"})]}),e.jsx("p",{className:"text-sm text-foreground/70 mb-4",children:"Manage who receives newsletter emails. Unchecking a subscriber will unsubscribe them and remove them from this list on refresh."}),A?e.jsx("div",{className:"flex items-center justify-center py-8",children:e.jsx("p",{className:"text-sm text-foreground/70",children:"Loading subscribers..."})}):R.length===0?e.jsx("div",{className:"flex items-center justify-center py-8",children:e.jsx("p",{className:"text-sm text-foreground/70",children:"No subscribers found"})}):e.jsx("div",{className:"overflow-y-auto flex-1 space-y-2",children:R.map(f=>e.jsxs("div",{className:"flex items-center gap-3 p-3 rounded-md border hover:bg-accent/50 transition-colors",children:[e.jsx("input",{type:"checkbox",checked:f.subscribed,onChange:()=>_e(f.user_id,f.subscribed),className:"w-4 h-4 rounded border-gray-300 cursor-pointer"}),e.jsxs("div",{className:"flex-1",children:[e.jsx("p",{className:"font-medium",children:f.name||"Unknown"}),e.jsx("p",{className:"text-sm text-foreground/70",children:f.email}),f.role&&e.jsx("span",{className:"inline-block text-xs bg-primary/10 text-primary px-2 py-0.5 rounded mt-1",children:f.role})]})]},f.user_id))}),e.jsxs("div",{className:"mt-4 pt-4 border-t flex justify-between items-center flex-shrink-0",children:[e.jsxs("p",{className:"text-sm text-foreground/70",children:["Total subscribers: ",R.length]}),e.jsx(w,{onClick:()=>T(!1),variant:"outline",children:"Close"})]})]})}),p&&e.jsx("div",{className:"fixed inset-0 bg-black/40 flex items-center justify-center z-50",onMouseDown:f=>{f.target===f.currentTarget&&(v(!1),c({}),x(null),I("Piano"),V({basic:!0,contact:!0,about:!1,media:!1}))},children:e.jsxs("div",{className:"bg-card rounded-md p-4 max-w-2xl w-full max-h-[90vh] flex flex-col",children:[e.jsxs("div",{className:"flex items-center justify-between mb-4 flex-shrink-0",children:[e.jsx("h3",{className:"text-lg font-semibold",children:u?"Edit teacher":"Add teacher"}),e.jsx(w,{variant:"ghost",onClick:()=>{v(!1),c({}),x(null),I("Piano"),V({basic:!0,contact:!0,about:!1,media:!1})},children:"Close"})]}),e.jsxs("form",{onSubmit:ve,className:"grid gap-1 flex-1 overflow-y-auto pr-2",children:[e.jsxs("div",{className:"border rounded-md",children:[e.jsxs("button",{type:"button",onClick:()=>V(f=>({...f,basic:!f.basic})),className:"w-full px-4 py-3 flex items-center justify-between hover:bg-muted/50 transition",children:[e.jsx("span",{className:"font-medium",children:"ð¤ Basic Info"}),e.jsx("span",{className:"text-sm",children:U.basic?"â¼":"â¶"})]}),U.basic&&e.jsxs("div",{className:"px-4 py-3 border-t bg-muted/20 space-y-2",children:[e.jsx("input",{id:"teacherName",name:"name",className:"w-full h-10 rounded-md border px-3",placeholder:"Name",value:l.name||"",onChange:f=>c(_=>({..._,name:f.target.value})),autoComplete:"name"}),e.jsx("input",{id:"teacherEmail",name:"email",className:"w-full h-10 rounded-md border px-3",placeholder:"Email",value:l.email||"",onChange:f=>c(_=>({..._,email:f.target.value})),autoComplete:"email"}),e.jsx("input",{id:"teacherPassword",name:"password",type:"password",className:"w-full h-10 rounded-md border px-3",placeholder:"Password (leave empty to keep current)",value:l.password||"",onChange:f=>c(_=>({..._,password:f.target.value})),autoComplete:"new-password"})]})]}),e.jsxs("div",{className:"border rounded-md",children:[e.jsxs("button",{type:"button",onClick:()=>V(f=>({...f,contact:!f.contact})),className:"w-full px-4 py-3 flex items-center justify-between hover:bg-muted/50 transition",children:[e.jsx("span",{className:"font-medium",children:"ð Contact & Experience"}),e.jsx("span",{className:"text-sm",children:U.contact?"â¼":"â¶"})]}),U.contact&&e.jsxs("div",{className:"px-4 py-3 border-t bg-muted/20 space-y-2",children:[e.jsx("input",{id:"teacherPhone",name:"phone",className:"w-full h-10 rounded-md border px-3",placeholder:"Phone",value:l.phone||"",onChange:f=>c(_=>({..._,phone:f.target.value})),autoComplete:"tel"}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs("label",{htmlFor:"teacherYears",className:"block text-sm font-medium",children:["Years:"," ",e.jsx("span",{className:"text-primary font-bold",children:l.years||0})]}),e.jsx("input",{id:"teacherYears",name:"years",type:"range",min:"0",max:"60",step:"1",className:"w-full h-2 bg-muted rounded-lg appearance-none cursor-pointer slider",style:{background:`linear-gradient(to right, hsl(var(--primary)) 0%, hsl(var(--primary)) ${(parseInt(l.years)||0)/60*100}%, hsl(var(--muted)) ${(parseInt(l.years)||0)/60*100}%, hsl(var(--muted)) 100%)`},value:l.years||0,onChange:f=>c(_=>({..._,years:f.target.value}))}),e.jsx("style",{children:` 10 .slider::-webkit-slider-thumb { 11 appearance: none;
12 width: 20px; 13 height: 20px; 14 border-radius: 50%; 15 background: hsl(var(--primary)); 16 cursor: pointer; 17 box-shadow: 0 2px 4px rgba(0,0,0,0.2); 18 transition: box-shadow 0.2s; 19 } 20 .slider::-webkit-slider-thumb:hover { 21 box-shadow: 0 2px 8px rgba(0,0,0,0.3); 22 } 23 .slider::-moz-range-thumb { 24 width: 20px; 25 height: 20px; 26 border-radius: 50%; 27 background: hsl(var(--primary)); 28 cursor: pointer; 29 border: none; 30 box-shadow: 0 2px 4px rgba(0,0,0,0.2); 31 transition: box-shadow 0.2s; 32 } 33 .slider::-moz-range-thumb:hover { 34 box-shadow: 0 2px 8px rgba(0,0,0,0.3); 35 } 36 `})]})]})]}),e.jsxs("div",{className:"border rounded-md",children:[e.jsxs("button",{type:"button",onClick:()=>V(f=>({...f,about:!f.about})),className:"w-full px-4 py-3 flex items-center justify-between hover:bg-muted/50 transition",children:[e.jsx("span",{className:"font-medium",children:"ð About & Visibility"}),e.jsx("span",{className:"text-sm",children:U.about?"â¼":"â¶"})]}),U.about&&e.jsxs("div",{className:"px-4 py-3 border-t bg-muted/20 space-y-3",children:[e.jsx("textarea",{id:"teacherAbout",name:"about",className:"w-full rounded-md border px-3 py-2 min-h-24",placeholder:"About",value:l.about||"",onChange:f=>c(_=>({..._,about:f.target.value}))}),e.jsxs("div",{className:"bg-card border rounded-md p-3 space-y-2",children:[e.jsx("p",{className:"text-sm font-medium",children:"Public visibility (optional)"}),e.jsxs("label",{className:"flex items-center gap-2 cursor-pointer",children:[e.jsx("input",{type:"checkbox",checked:l.phonePublic||!1,onChange:f=>c(_=>({..._,phonePublic:f.target.checked})),className:"w-4 h-4"}),e.jsx("span",{className:"text-sm",children:"Show phone number publicly"})]}),e.jsxs("label",{className:"flex items-center gap-2 cursor-pointer",children:[e.jsx("input",{type:"checkbox",checked:l.emailPublic||!1,onChange:f=>c(_=>({..._,emailPublic:f.target.checked})),className:"w-4 h-4"}),e.jsx("span",{className:"text-sm",children:"Show email publicly"})]})]})]})]}),e.jsxs("div",{className:"border rounded-md",children:[e.jsxs("button",{type:"button",onClick:()=>V(f=>({...f,media:!f.media})),className:"w-full px-4 py-3 flex items-center justify-between hover:bg-muted/50 transition",children:[e.jsx("span",{className:"font-medium",children:"ðµ Media & Skills"}),e.jsx("span",{className:"text-sm",children:U.media?"â¼":"â¶"})]}),U.media&&e.jsxs("div",{className:"px-4 py-3 border-t bg-muted/20 space-y-3",children:[e.jsxs("div",{children:[e.jsx("label",{htmlFor:"teacherImage",className:"block text-sm font-medium mb-2",children:"Profile picture"}),e.jsxs("div",{onDrop:Ce,onDragOver:f=>f.preventDefault(),className:"border-dashed border-2 border-gray-300 rounded-md p-3 text-sm text-center",children:[l.image?e.jsx("img",{src:l.image,alt:"preview",className:"mx-auto h-20 object-cover rounded-md"}):e.jsx("div",{className:"text-foreground/70",children:"Drop image here or choose"}),e.jsx("input",{id:"teacherImage",name:"image",type:"file",accept:"image/*",onChange:xe,className:"mt-2 w-full"})]})]}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-medium mb-2",children:"Instruments taught"}),e.jsxs("div",{className:"flex gap-2 flex-wrap mb-2",children:[e.jsx("select",{value:y,onChange:f=>I(f.target.value),className:"h-10 rounded-md border px-3 flex-1 min-w-32",children:["Piano","Keyboard","Guitar","Bass","Drums","Voice","Singing"].map(f=>e.jsx("option",{value:f,children:f},f))}),e.jsx("button",{type:"button",onClick:pe,className:"px-3 py-2 rounded-md border hover:bg-muted",children:"Add"})]}),e.jsx("div",{className:"flex gap-2 flex-wrap",children:(l.instruments||[]).map(f=>e.jsxs("div",{className:"px-3 py-1 rounded-md bg-primary text-primary-foreground text-sm flex items-center gap-2",children:[f,e.jsx("button",{type:"button",onClick:()=>Ne(f),className:"text-xs hover:opacity-75",children:"Ã"})]},f))})]})]})]}),e.jsxs("div",{className:"sticky bottom-0 bg-card border-t p-3 flex gap-2 flex-wrap",children:[e.jsx(w,{type:"submit",className:"px-4 py-2",variant:"default",children:u?"Save":"Add"}),e.jsx(w,{type:"button",onClick:()=>{c({}),x(null),I("Piano"),V({basic:!0,contact:!0,about:!1,media:!1})},variant:"outline",children:"Clear"}),e.jsx(w,{type:"button",onClick:be,variant:"ghost",children:n?"Loading...":"Random"}),u&&e.jsx(w,{type:"button",onClick:async()=>
36{if(confirm("Are you sure you want to delete this teacher? This action cannot be undone."))try{const{apiFetch:f}=await Y(async()=>{const{apiFetch:re}=await import("./api-CyvozDRd.js");return{apiFetch:re}},[]);await f(`/api/admin/teachers/${u}`,{method:"DELETE"}),S({title:"Teacher deleted"}),c({}),x(null),v(!1),I("Piano"),V({basic:!0,contact:!0,about:!1,media:!1});const _=await ot();t(_)}catch(f){console.error(f),S({title:"Error",description:"Failed to delete teacher"})}},variant:"destructive",children:"ðï¸ Delete"})]})]})]})})]})}function ir(a=12){const t="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789!@#$%^&*()_+~`|}{[]:;?><,./-=";let s="";for(let r=0;r<a;r++)s+=t[Math.floor(Math.random()*t.length)];return s}function or({t:a,onEdit:t,onRemove:s}){const[r,n]=m.useState(!1);return e.jsxs("div",{className:"rounded-lg border overflow-hidden hover:shadow-lg transition-shadow flex flex-col",children:[e.jsxs("div",{className:"flex flex-col sm:flex-row flex-1",children:[e.jsx("img",{src:a.image||"https://images.unsplash.com/photo-1524504388940-b1c1722653e1?w=400&q=60",alt:a.name,className:"w-full sm:w-28 h-28 object-cover"}),e.jsxs("div",{className:"p-4 flex-1 flex flex-col",children:[e.jsxs("div",{children:[e.jsx("div",{className:"font-semibold text-lg",children:a.name}),e.jsx("div",{className:"text-sm text-foreground/70",children:a.years?`${a.years} years experience`:"Experience: N/A"}),e.jsx("div",{className:"text-sm text-foreground/70",children:a.email})]}),a.about&&e.jsx("p",{className:"mt-3 text-sm text-foreground/70",children:a.about}),e.jsxs("div",{className:"mt-3",children:[e.jsx("button",{onClick:()=>n(i=>!i),className:"text-sm text-primary underline hover:opacity-70",children:r?"Hide profile":"View full profile"}),r&&e.jsxs("div",{className:"mt-3 p-3 bg-muted rounded-md",children:[e.jsx("p",{className:"text-sm",children:a.about||"No description"}),e.jsxs("p",{className:"text-xs text-foreground/60 mt-2",children:["Contact: ",a.email," ",a.phone&&`⢠${a.phone}`]})]})]})]})]}),e.jsxs("div",{className:"flex gap-2 p-4 border-t bg-muted/30",children:[e.jsx("button",{onClick:t,className:"flex-1 px-3 py-2 rounded-md bg-primary text-primary-foreground text-sm font-medium hover:opacity-90 transition",children:"âï¸ Edit"}),e.jsx("button",{onClick:s,className:"flex-1 px-3 py-2 rounded-md bg-destructive text-destructive-foreground text-sm font-medium hover:opacity-90 transition",children:"ðï¸ Remove"})]})]})}function lr(){const a={blue:{primary:"200 100% 41%",brand1:"200 100% 41%",brand2:"200 70% 71%",secondary:"200 70% 71%"},grey:{primary:"220 6% 20%",brand1:"220 6% 20%",brand2:"220 6% 35%",secondary:"220 6% 35%"},white:{primary:"0 0% 10%",brand1:"0 0% 10%",brand2:"0 0% 20%",secondary:"0 0% 20%"},purple:{primary:"270 80% 45%",brand1:"270 80% 45%",brand2:"265 60% 60%",secondary:"265 60% 60%"},yellow:{primary:"48 100% 50%",brand1:"48 100% 50%",brand2:"48 80% 70%",secondary:"48 80% 70%"}},{setMode:t,saveTheme:s,previewTheme:r,restoreTheme:n}=ps(),[i,l]=m.useState("blue"),[c,u]=m.useState(a.blue.primary),[x,p]=m.useState(a.blue.brand1),[v,y]=m.useState(a.blue.brand2),[I,U]=m.useState(a.blue.secondary),[V,L]=m.useState("#008CD2"),[G,W]=m.useState("#008CD2"),[ne,E]=m.useState("#C8E7F6"),[d,C]=m.useState("#C8E7F6"),[k,b]=m.useState(!1),[F,T]=m.useState(()=>{try{return localStorage.getItem("inTuneThemeMode")==="dark"?"dark":"light"}catch{return"light"}});m.useEffect(()=>{const S=localStorage.getItem("inTuneTheme");if(S)try{const N=JSON.parse(S);u(N.primary||c),p(N.brand1||x),y(N.brand2||v),U(N.secondary||I)}catch{}},[]);const R=S=>{S=S.replace("#","");const N=parseInt(S,16),oe=N>>16&255,_e=N>>8&255,ve=N&255,le=oe/255,ce=_e/255,pe=ve/255,Ne=Math.max(le,ce,pe),be=Math.min(le,ce,pe);let ye=0,Ce=0,xe=(Ne+be)/2;if(Ne!==be){const he=Ne-be;switch(Ce=xe>.5?he/(2-Ne-be):he/(Ne+be),Ne){case le:ye=(ce-pe)/he+(ce<pe?6:0);break;case ce:ye=(pe-le)/he+2;break;case pe:ye=(le-ce)/he+4;break}ye=Math.round(ye*60)}return Ce=Math.round(Ce*100),xe=Math.round(xe*100),`${ye} ${Ce}% ${xe}%`};m.useEffect(()=>{a[i]&&(u(a[i].primary),p(a[i].brand1),y(a[i].brand2),U(a[i].secondary))},[i]);const M=()=>{r({primary:c,brand1:x,brand2:v,secondary:I}),b(!0)},A=()=>{s({primary:c,brand1:x,brand2:v,secondary:I}),b(!1),alert("Theme saved")},te=()=>{n(),b(!1)};return m.useEffect(()=>{if(!k)return;const S=N=>{N.key==="Escape"&&te()};return window.addEventListener("keydown",S),()=>window.removeEventListener("keydown",S)},[k]),e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{children:[e.jsx("h3",{className:"text-sm font-semibold text-foreground mb-3",children:"Color Presets"}),e.jsx("div",{className:"grid grid-cols-2 sm:grid-cols-3 gap-2",children:Object.entries(a).map(([S,N])=>e.jsxs("button",{onClick:()=>l(S),className:`relative group p-3 rounded-lg border-2 transition-all ${i===S?"border-primary bg-primary/5":"border-border hover:border-primary/50"}`,children:[e.jsxs("div",{className:"flex gap-1.5 mb-2",children:[e.jsx("div",{className:"w-4 h-4 rounded-full",style:{backgroundColor:`hsl(${N.primary})`},title:"Primary"}),e.jsx("div",{className:"w-4 h-4 rounded-full",style:{backgroundColor:`hsl(${N.brand1})`},title:"Brand 1"}),e.jsx("div",{className:"w-4 h-4 rounded-full",style:{backgroundColor:`hsl(${N.brand2})`},title:"Brand 2"}),e.jsx("div",{className:"w-4 h-4 rounded-full",style:{backgroundColor:`hsl(${N.secondary})`},title:"Secondary"})]}),e.jsx("span",{className:"text-xs font-medium capitalize text-foreground",children:S})]},S))})]}),e.jsxs("div",{className:"space-y-4",children:[e.jsx("h3",{className:"text-sm font-semibold text-foreground",children:"Colors"}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("label",{className:"text-sm font-medium text-foreground",children:"Primary"}
36),e.jsx("span",{className:"text-xs text-foreground/50",children:"Main brand color"})]}),e.jsxs("div",{className:"flex gap-3 items-center",children:[e.jsx("input",{type:"color",className:"h-12 w-16 rounded-md border cursor-pointer",value:V,onChange:S=>{L(S.target.value),u(R(S.target.value)),p(R(S.target.value)),W(S.target.value)}}),e.jsx("div",{className:"flex-1",children:e.jsx("input",{className:"text-xs h-8 rounded-md border px-2 w-full bg-background",placeholder:"H S% L%",value:c,onChange:S=>u(S.target.value)})})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("label",{className:"text-sm font-medium text-foreground",children:"Brand 1"}),e.jsx("span",{className:"text-xs text-foreground/50",children:"Primary accent color"})]}),e.jsxs("div",{className:"flex gap-3 items-center",children:[e.jsx("input",{type:"color",className:"h-12 w-16 rounded-md border cursor-pointer",value:G,onChange:S=>{W(S.target.value),p(R(S.target.value))}}),e.jsx("div",{className:"flex-1",children:e.jsx("input",{className:"text-xs h-8 rounded-md border px-2 w-full bg-background",placeholder:"H S% L%",value:x,onChange:S=>p(S.target.value)})})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("label",{className:"text-sm font-medium text-foreground",children:"Brand 2"}),e.jsx("span",{className:"text-xs text-foreground/50",children:"Secondary accent color"})]}),e.jsxs("div",{className:"flex gap-3 items-center",children:[e.jsx("input",{type:"color",className:"h-12 w-16 rounded-md border cursor-pointer",value:ne,onChange:S=>{E(S.target.value),y(R(S.target.value))}}),e.jsx("div",{className:"flex-1",children:e.jsx("input",{className:"text-xs h-8 rounded-md border px-2 w-full bg-background",placeholder:"H S% L%",value:v,onChange:S=>y(S.target.value)})})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("label",{className:"text-sm font-medium text-foreground",children:"Secondary"}),e.jsx("span",{className:"text-xs text-foreground/50",children:"Supporting color"})]}),e.jsxs("div",{className:"flex gap-3 items-center",children:[e.jsx("input",{type:"color",className:"h-12 w-16 rounded-md border cursor-pointer",value:d,onChange:S=>{C(S.target.value),U(R(S.target.value))}}),e.jsx("div",{className:"flex-1",children:e.jsx("input",{className:"text-xs h-8 rounded-md border px-2 w-full bg-background",placeholder:"H S% L%",value:I,onChange:S=>U(S.target.value)})})]})]})]}),e.jsxs("div",{className:"flex gap-2 pt-2",children:[e.jsx("button",{onClick:M,className:"flex-1 px-4 py-2 rounded-md bg-primary text-primary-foreground font-medium hover:bg-primary/90 transition",children:"Preview"}),e.jsx("button",{onClick:A,className:"flex-1 px-4 py-2 rounded-md border border-primary bg-primary/5 text-primary font-medium hover:bg-primary/10 transition",children:"Save"})]}),k&&e.jsx("div",{className:"fixed inset-0 bg-black/40 flex items-center justify-center z-40",onMouseDown:S=>{S.target===S.currentTarget&&te()},children:e.jsxs("div",{className:"flex flex-col items-center gap-3",children:[e.jsx("div",{className:"p-1 rounded-full bg-card border",children:e.jsx("button",{onClick:()=>{T(S=>S==="dark"?"light":"dark")},className:"p-2 rounded-full",children:F==="dark"?e.jsx("svg",{className:"w-5 h-5 text-foreground",viewBox:"0 0 24 24",fill:"currentColor",children:e.jsx("path",{d:"M21 12.79A9 9 0 1111.21 3 7 7 0 0021 12.79z"})}):e.jsx("svg",{className:"w-5 h-5 text-foreground",viewBox:"0 0 24 24",fill:"currentColor",children:e.jsx("path",{d:"M6.76 4.84l-1.8-1.79L3.17 4.84l1.79 1.79 1.8-1.79zM1 13h3v-2H1v2zm10 9h2v-3h-2v3zM6.76 19.16l1.79-1.79-1.79-1.79-1.8 1.79 1.8 1.79zM20 11v2h3v-2h-3zM17.24 19.16l1.8-1.79 1.79 1.79-1.79 1.79-1.8-1.79zM12 4a8 8 0 100 16 8 8 0 000-16z"})})})}),e.jsx("div",{className:"bg-card rounded-md p-3 w-[380px] max-w-full",children:e.jsx(wa,{mode:F,setMode:T,compact:!0})}),e.jsxs("div",{className:"w-[380px] max-w-full flex items-center justify-between",children:[e.jsx("button",{onClick:()=>{te()},className:"px-4 py-2 rounded-md bg-destructive text-destructive-foreground",children:"Cancel"}),e.jsx("button",{onClick:()=>{t(F),A()},className:"px-4 py-2 rounded-md bg-primary text-primary-foreground",children:"Apply"})]})]})})]})}function dr(){const a=new Date().toISOString().slice(0,10),[t,s]=m.useState(0),[r,n]=m.useState(0),[i,l]=m.useState(0),[c,u]=m.useState(!0),[x,p]=m.useState(null);m.useEffect(()=>{let y=!0;async function I(){try{u(!0);const V=await Je.list();if(!y)return;s(Array.isArray(V)?V.length:0);const L=await qt(a);if(!y)return;n(Array.isArray(L)?L.length:0);const G=new Date(a);G.setDate(G.getDate()-G.getDay());const W=await qt(G.toISOString().slice(0,10));if(!y)return;l(Array.isArray(W)?W.length:0),p(new Date)}catch(V){console.error(V)}finally{y&&u(!1)}}I();const U=setInterval(I,1e4);return()=>{y=!1,clearInterval(U)}},[a]);const v=({icon:y,label:I,value:U,sublabel:V,bgColor:L})=>e.jsx("div",{className:"rounded-lg border bg-card hover:shadow-md transition-shadow overflow-hidden",children:e.jsxs("div",{className:"p-4",children:[e.jsxs("div",{className:"flex items-start justify-between mb-3",children:[e.jsx("div",{className:`p-2 rounded-lg ${L}`,children:y}
36),c&&e.jsx("div",{className:"h-1 w-12 bg-foreground/20 rounded-full animate-pulse"})]}),e.jsx("div",{className:"text-sm font-medium text-foreground/70",children:I}),e.jsx("div",{className:"text-3xl font-bold text-foreground mt-1",children:c?"-":U}),V&&e.jsx("div",{className:"text-xs text-foreground/50 mt-2",children:V})]})});return e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("h3",{className:"text-sm font-semibold text-foreground",children:"Dashboard Metrics"}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("div",{className:"text-xs text-foreground/50",children:x&&e.jsxs(e.Fragment,{children:["Updated"," ",Math.round((new Date().getTime()-x.getTime())/1e3)," ","ago"]})}),e.jsx("div",{className:`w-2 h-2 rounded-full ${c?"bg-yellow-500 animate-pulse":"bg-green-500 animate-pulse"}`})]})]}),e.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-4 gap-4",children:[e.jsx(v,{icon:e.jsx("svg",{className:"w-5 h-5 text-blue-600",fill:"currentColor",viewBox:"0 0 24 24",children:e.jsx("path",{d:"M12 2C6.48 2 2 6.48 2 12s4.48 10 10 10 10-4.48 10-10S17.52 2 12 2zm0 3c1.66 0 3 1.34 3 3s-1.34 3-3 3-3-1.34-3-3 1.34-3 3-3zm0 14.2c-2.5 0-4.71-1.28-6-3.22.03-1.99 4-3.08 6-3.08 1.99 0 5.97 1.09 6 3.08-1.29 1.94-3.5 3.22-6 3.22z"})}),label:"Total Students",value:t,sublabel:`${t} active`,bgColor:"bg-blue-100 dark:bg-blue-900/30"}),e.jsx(v,{icon:e.jsx("svg",{className:"w-5 h-5 text-green-600",fill:"currentColor",viewBox:"0 0 24 24",children:e.jsx("path",{d:"M19 3H5c-1.1 0-2 .9-2 2v14c0 1.1.9 2 2 2h14c1.1 0 2-.9 2-2V5c0-1.1-.9-2-2-2zm0 16H5V5h14v14zm-5.04-6.71l-2.75 3.54-2.12-2.58c-.3-.36-.77-.58-1.3-.58-.98 0-1.81.94-1.81 2.12 0 .59.26 1.12.68 1.49h2.04l3.02-3.87 4.12 5.06h2.04l-4.88-6.05c-.3-.37-.77-.59-1.3-.59-.98 0-1.81.94-1.81 2.12z"})}),label:"Lessons Today",value:r,sublabel:`${r} scheduled`,bgColor:"bg-green-100 dark:bg-green-900/30"}),e.jsx(v,{icon:e.jsx("svg",{className:"w-5 h-5 text-purple-600",fill:"currentColor",viewBox:"0 0 24 24",children:e.jsx("path",{d:"M17 12h-5v5h5v-5zM16 1v2H8V1H6v2H5c-1.1 0-2 .9-2 2v14c0 1.1.9 2 2 2h14c1.1 0 2-.9 2-2V5c0-1.1-.9-2-2-2h-1V1h-2zm3 15H5V8h14v8z"})}),label:"This Week",value:i,sublabel:`${i} lessons scheduled`,bgColor:"bg-purple-100 dark:bg-purple-900/30"}),e.jsx(v,{icon:e.jsx("svg",{className:"w-5 h-5 text-amber-600",fill:"currentColor",viewBox:"0 0 24 24",children:e.jsx("path",{d:"M12 2C6.48 2 2 6.48 2 12s4.48 10 10 10 10-4.48 10-10S17.52 2 12 2zm-2 15l-5-5 1.41-1.41L10 14.17l7.59-7.59L19 8l-9 9z"})}),label:"System Status",value:"Active",sublabel:"All systems operational",bgColor:"bg-amber-100 dark:bg-amber-900/30"})]}),e.jsx("div",{className:"text-xs text-foreground/50 p-3 rounded-lg bg-foreground
36/5",children:"ð Metrics update automatically every 10 seconds. Click on any metric to view details."})]})}const cr=new Set(["pdf","zip","doc","docx","txt","rtf","mp4","mov","avi","mkv","mp3","wav","ogg","m4a","aac","flac","ppt","pptx","xls","xlsx"]),ur=new Set(["application/pdf","application/zip","application/msword","application/vnd.openxmlformats-officedocument.wordprocessingml.document","application/vnd.ms-powerpoint","application/vnd.openxmlformats-officedocument.presentationml.presentation","application/vnd.ms-excel","application/vnd.openxmlformats-officedocument.spreadsheetml.sheet","text/plain"]),mr=["video/","audio/"],vt=a=>`${a.name}-${a.size}-${a.lastModified}`;function hr(a){if(ur.has(a.type)||mr.some(s=>a.type.startsWith(s)))return!0;const t=a.name.split(".").pop()?.toLowerCase();return t?cr.has(t):!1}function pr(){const[a,t]=m.useState(""),{toast:s}=Pe(),r=["Guitar","Piano","Keyboard","Drums","Bass","Voice","Singing"],[n,i]=m.useState([]),l=(()=>{const o=new Date;return o.setFullYear(o.getFullYear()-16),o.toISOString().slice(0,10)})();function c(o){if(!o)return;const g=new Date(o);if(Number.isNaN(g.getTime()))return;const z=new Date;let Z=z.getFullYear()-g.getFullYear();const K=z.getMonth()-g.getMonth();return(K<0||K===0&&z.getDate()<g.getDate())&&Z--,Z}const[u,x]=m.useState({name:"",profilePicture:null,dob:l,medications:"",marketingConsent:!1,allergies:"",instruments:[],bandName:"",email:"",phone:"",address:"",emergencyContacts:"",parentGuardianName:"",parentGuardianEmail:"",parentGuardianPhone:""}),[p,v]=m.useState(null),[y,I]=m.useState(r[0]),[U,V]=m.useState(null),[L,G]=m.useState(""),[W,ne]=m.useState(!1),[E,d]=m.useState([]),[C,k]=m.useState(""),[b,F]=m.useState(""),T=m.useRef(null),[R,M]=m.useState(!1),[A,te]=m.useState({}),[S,N]=m.useState(!1),[oe,_e]=m.useState(null),[ve,le]=m.useState([]),[ce,pe]=m.useState(!1),[Ne,be]=m.useState(!1),ye=m.useMemo(()=>{const o=L.trim().toLowerCase();return o?n.filter(g=>{const z=[],Z=K=>{typeof K=="string"&&K.trim().length>0&&z.push(K.toLowerCase())};return Z(g.name),Z(g.email),Z(g.phone),Z(g.address),Z(g.bandName),Z(g.parentGuardianName),Z(g.parentGuardianEmail),Z(g.parentGuardianPhone),Z(g.parent_name),Z(g.parent_email),Z(String(g.age??"")),Array.isArray(g.instruments)&&g.instruments.forEach(Z),z.some(K=>K.includes(o))}):n},[n,L]),Ce=L.trim().length>0,xe=m.useMemo(()=>n.map(o=>{const g=o.student_id||o.id||"";return g?{value:g,label:o.name||o.email||g}:null}).filter(o=>o!==null),[n]);m.useEffect(()=>{!W||xe.length===0||(k(o=>o&&xe.some(g=>g.value===o)?o:xe[0].value),F(()=>`${new Date().toISOString().slice(0,10)} - `))},[W,xe]);const he=m.useCallback(()=>{d([]),F(""),T.current&&(T.current.value="")},[T]);m.useCallback(()=>{if(!n.length){s({title:"No students available",description:"Add a student before uploading resources.",variant:"destructive"});return}he(),ne(!0)},[n,s,he]);const $=m.useCallback(()=>{R||(he(),ne(!1))},[he,R]),Q=m.useCallback(o=>{if(!o)return;const g=Array.isArray(o)?[...o]:Array.from(o);if(!g.length)return;const z=[],Z=[];g.forEach(K=>{hr(K)?z.push(K):Z.push(K.name)}),Z.length&&s({title:"Unsupported files skipped",description:Z.join(", "),variant:"destructive"}),z.length&&d(K=>{const ee=new Map(K.map(ie=>[vt(ie),ie]));return z.forEach(ie=>{ee.set(vt(ie),ie)}),Array.from(ee.values())})},[s]),f=m.useCallback(o=>{o.preventDefault(),o.dataTransfer?.files?.length&&Q(o.dataTransfer.files)},[Q]),_=m.useCallback(o=>{o.target.files?.length&&Q(o.target.files),T.current&&(T.current.value="")},[Q]),re=m.useCallback(o=>{d(g=>g.filter(z=>vt(z)!==o))},[]),je=m.useCallback(async()=>{if(!C){s({title:"Select a student",description:"Choose who should receive the resources.",variant:"destructive"});return}if(E.length===0){s({title:"Add files",description:"Drag and drop or select files to share.",variant:"destructive"});return}const o=E.filter(g=>{const z=g.type.startsWith("image/")?4194304:104857600;return g.size>z});if(o.length>0){s({title:"Files too large",description:`${o.length} file(s) too large: ${o.map(g=>`${g.name} (${Math.round(g.size/1024/1024)}MB)`).join(", ")}. Images: max 4MB, Videos/Audio: max 100MB.`,variant:"destructive"});return}try{M(!0);const{uploadMedia:g}=await Y(async()=>{const{uploadMedia:K}=await import("./uploadMedia-BPkFDiJH.js");return{uploadMedia:K}},__vite__mapDeps([0,1])),z=[];for(const K of E){const ee=await g(K);z.push(ee)}const{apiFetch:Z}=await Y(async()=>{const{apiFetch:K}=await import("./api-CyvozDRd.js");return{apiFetch:K}},[]);await Z(`/api/admin/learning/${C}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({title:b&&b.trim()?b.trim():"Learning resources",description:"",media:z})}),s({title:"Resources uploaded",description:`${E.length} file${E.length>
361?"s":""} shared with the student.`}),he(),ne(!1)}catch(g){s({title:"Upload failed",description:g?.message||"Unable to upload resources.",variant:"destructive"})}finally{M(!1)}},[E,C,s,he]),Fe=W?e.jsx("div",{className:"fixed inset-0 z-50 flex items-center justify-center bg-black/50 p-4",onMouseDown:o=>{o.target===o.currentTarget&&$()},children:e.jsxs("div",{className:"w-full max-w-2xl rounded-lg bg-card p-6 shadow-xl",onMouseDown:o=>o.stopPropagation(),children:[e.jsxs("div",{className:"flex flex-col gap-2 sm:flex-row sm:items-start sm:justify-between",children:[e.jsxs("div",{children:[e.jsx("h3",{className:"text-lg font-semibold",children:"Upload learning resources"}),e.jsx("p",{className:"text-sm text-foreground/70",children:"Drag and drop or select files to share with a student."})]}),e.jsx(w,{type:"button",variant:"ghost",onClick:$,disabled:R,children:"Close"})]}),e.jsxs("div",{className:"mt-4 grid gap-3",children:[e.jsxs("div",{children:[e.jsx("label",{htmlFor:"resourceFolder",className:"mb-1 block text-sm font-medium text-foreground",children:"Folder name"}),e.jsx("input",{id:"resourceFolder",className:"h-10 w-full rounded-md border px-3",value:b,onChange:o=>F(o.target.value),placeholder:"e.g. 2025-01-01 - Week 1 materials",disabled:R})]}),e.jsxs("div",{children:[e.jsx("label",{htmlFor:"resourceStudent",className:"mb-1 block text-sm font-medium text-foreground",children:"Student"}),e.jsx("select",{id:"resourceStudent",className:"h-10 w-full rounded-md border px-3",value:C,onChange:o=>k(o.target.value),disabled:xe.length===0||R,children:xe.map(o=>e.jsx("option",{value:o.value,children:o.label},o.value))})]}),e.jsxs("div",{children:[e.jsxs("div",{onDrop:f,onDragOver:o=>o.preventDefault(),className:"flex flex-col items-center justify-center gap-2 rounded-md border-2 border-dashed border-muted-foreground/40 bg-muted/20 p-6 text-center text-sm",children:[e.jsx("p",{className:"font-medium",children:"Drop files here"}),e.jsx("p",{className:"text-xs text-foreground/70",children:"Accepted: pdf, zip, doc, docx, txt, rtf, video formats and more"}),e.jsx(w,{type:"button",variant:"outline",size:"sm",onClick:()=>T.current?.click(),disabled:R,children:"Select files"})]}),e.jsx("input",{ref:T,type:"file",multiple:!0,accept:"application/pdf,application/zip,application/msword,application/vnd.openxmlformats-officedocument.wordprocessingml.document,application/vnd.ms-powerpoint,application/vnd.openxmlformats-officedocument.presentationml.presentation,application/vnd.ms-excel,application/vnd.openxmlformats-officedocument.spreadsheetml.sheet,text/plain,video/*,.doc,.docx,.pdf,.zip,.txt,.rtf,.ppt,.pptx,.xls,.xlsx,.mp4,.mov,.avi,.mkv",className:"hidden",onChange:_})]}),E.length>0?e.jsx("ul",{className:"space-y-2 rounded-md border bg-muted/40 p-3 text-sm",children:E.map(o=>{const g=vt(o),z=o.size/(1024*1024),Z=z>=1?`${z.toFixed(1)} MB`:`${Math.max(1,Math.round(o.size/1024))} KB`;return e.jsxs("li",{className:"flex items-center justify-between gap-2",children:[e.jsx("span",{className:"flex-1 truncate",children:o.name}),e.jsx("span",{className:"text-xs text-foreground/70",children:Z}),e.jsx(w,{type:"button",variant:"ghost",size:"sm",onClick:()=>re(g),disabled:R,children:"Remove"})]},g)})}):e.jsx("div",{className:"rounded-md border border-dashed p-4 text-xs text-foreground/60",children:"No files selected yet."}),e.jsxs("div",{className:"flex flex-col gap-2 sm:flex-row sm:justify-end",children:[e.jsx(w,{type:"button",variant:"outline",onClick:he,disabled:E.length===0||R,className:"w-full sm:w-auto",children:"Clear files"}),e.jsx(w,{type:"button",onClick:je,disabled:R,className:"w-full sm:w-auto",children:R?"Uploading...":"Share resources"})]})]})]})}):null,qe=S?e.jsx("div",{className:"fixed inset-0 z-50 flex items-center justify-center bg-black/50 p-4",onMouseDown:o=>{o.target===o.currentTarget&&N(!1)},children:e.jsxs("div",{className:"w-full max-w-3xl rounded-lg bg-card p-6 shadow-xl",onMouseDown:o=>o.stopPropagation(),children:[e.jsxs("div",{className:"flex items-start justify-between",children:[e.jsxs("div",{children:[e.jsx("h3",{className:"text-lg font-semibold",children:"View resources"}
36),e.jsx("p",{className:"text-sm text-foreground/70",children:"Resources shared with the selected student. You may remove items if needed."})]}),e.jsx("div",{className:"flex items-center gap-2",children:e.jsx(w,{variant:"ghost",onClick:()=>N(!1),disabled:Ne,children:"Close"})})]}),e.jsx("div",{className:"mt-4",children:ce?e.jsx("div",{className:"text-sm text-foreground/70",children:"Loadingâ¦"}):ve.length===0?e.jsx("div",{className:"rounded border border-dashed p-4 text-sm text-foreground/70",children:"No resources found for this student."}):e.jsx("div",{className:"space-y-3",children:ve.map(o=>e.jsxs("div",{className:"rounded border p-3",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx("div",{className:"font-semibold",children:o.title||"Resource"}),e.jsx("div",{className:"text-xs text-foreground/70",children:o.created_at?new Date(o.created_at).toLocaleString():""})]}),e.jsx("div",{className:"flex items-center gap-2",children:e.jsx(w,{size:"sm",variant:"destructive",onClick:async()=>{if(confirm("Delete this resource folder and all its files?"))try{be(!0);const{apiFetch:g}=await Y(async()=>{const{apiFetch:Z}=await import("./api-CyvozDRd.js");return{apiFetch:Z}},[]);await g(`/api/admin/learning/entry/${o.id}`,{method:"DELETE"});const z=await g(`/api/admin/learning/${oe}`);le(Array.isArray(z)?z:z&&z.rows||[])}catch(g){console.error(g),s({title:"Failed to delete folder",variant:"destructive"})}finally{be(!1)}},children:"Delete folder"})})]}),Array.isArray(o.media)&&o.media.length>0&&e.jsx("div",{className:"mt-3 grid gap-2 md:grid-cols-2",children:o.media.map(g=>e.jsxs("div",{className:"flex items-center justify-between gap-2 rounded border p-2",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[g.mime?.startsWith("image")?e.jsx("img",{src:g.url,alt:"",className:"h-16 w-24 object-cover rounded"}):g.mime?.startsWith("video")?e.jsx("video",{src:g.url,className:"h-16 w-24 object-cover"}):e.jsx("a",{href:g.url,target:"_blank",rel:"noreferrer",className:"underline",children:"Open file"}),e.jsx("div",{className:"text-sm",children:g.url.split("/").pop()})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(w,{size:"sm",variant:"outline",onClick:()=>window.open(g.url,"_blank"),children:"Open"}),e.jsx(w,{size:"sm",variant:"destructive",onClick:async()=>{if(confirm("Remove this file from the resource folder?"))try{be(!0);const{apiFetch:z}=await Y(async()=>{const{apiFetch:K}=await import("./api-CyvozDRd.js");return{apiFetch:K}},[]),Z=await z(`/api/admin/learning/entry/${o.id}/media/${g.id}`,{method:"DELETE"});le(Array.isArray(Z)?Z:Z&&Z.rows||[])}catch(z){console.error(z),s({title:"Failed to remove file",variant:"destructive"})}finally{be(!1)}},children:"Remove"})]})]},g.id||g.url))})]},o.id))})})]})}):null,st=o=>{o&&te(g=>({...g,[o]:!g[o]}))},Be=o=>{if(!o)return"â";const g=new Date(o);return Number.isNaN(g.getTime())?"â":g.toLocaleString(void 0,{dateStyle:"medium",timeStyle:"short"})},at=async()=>{try{const o=await Je.list();i(Array.isArray(o)?o:[])}catch(o){console.error(o),i([])}};m.useEffect(()=>{at()},[]);const kt=async o=>{o&&o.preventDefault();const g=u.name?.trim();if(!g){alert("Name is required");return}const z=c(u.dob),Z=typeof z=="number"&&!Number.isNaN(z)?z:null,K=u.emergencyContacts?.trim()||"";if(!K){alert("Emergency contact is required");return}const ee=u.parentGuardianName?.trim()||"",ie=u.parentGuardianPhone?.trim()||"",de=u.parentGuardianEmail?.trim()||"",He=u.email?.trim()||"";if(X&&(!ee||!ie||!de)){alert("Parent or guardian name, phone and email are required for students under 16");return}const mt=X?de:He;if(!mt){alert(X?"Parent or guardian email is required for students under 16":"Email is required");return}const ht=u.phone?.trim()||"",pt={name:g,age:Z,parent_name:X?ee:null,parent_email:X?de:null,parent_phone:X?ie:null,phone:(X?ie:ht)||ht||ie||""||null,address:u.address?.trim()||null,marketing_consent:!!u.marketingConsent,email:mt,emergency_contacts:K,allergies:u.allergies?.trim()||null,medications:u.medications?.trim()||null,instruments:u.instruments||[],band:u.bandName?.trim()||null};let ys=null;if(p&&u.profilePicture)try{const Ee=u.profilePicture,Vt=await(Se=>new Promise((Tt,Et)=>{const Re=new FileReader;Re.onload=()=>
36Tt(Re.result.split(",")[1]),Re.onerror=Et,Re.readAsDataURL(Se)}))(Ee),{apiFetch:St}=await Y(async()=>{const{apiFetch:Se}=await import("./api-CyvozDRd.js");return{apiFetch:Se}},[]),nt=await St("/api/admin/upload-profile-picture",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({data:Vt,studentId:p})});if(!nt.ok){const Se=await nt.json().catch(()=>({}));throw new Error(Se.error||Se.message||"Failed to upload profile picture")}const it=await nt.json();pt.profile_picture_url=it.url,ys=it.url}catch(Ee){console.error("Profile picture upload failed:",Ee),alert(`Failed to upload profile picture: ${Ee.message}`);return}try{let Ee=null;if(p)await Je.update(p,pt);else{const fe=await Je.create({...pt,tempPassword:pt.email});Ee=fe?.id||fe?.student_id||null}if(!p&&u.profilePicture&&Ee)try{const fe=u.profilePicture,St=await(Se=>new Promise((Tt,Et)=>{const Re=new FileReader;Re.onload=()=>Tt(Re.result.split(",")[1]),Re.onerror=Et,Re.readAsDataURL(Se)}))(fe),{apiFetch:nt}=await Y(async()=>{const{apiFetch:Se}=await import("./api-CyvozDRd.js");return{apiFetch:Se}},[]),it=await nt("/api/admin/upload-profile-picture",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({data:St,studentId:Ee})});if(it.ok){const Se=await it.json();console.log("â
Profile picture uploaded for new student:",Se.url)}else console.error("â ï¸ Profile picture upload failed for new student")}catch(fe){console.error("Profile picture upload failed (non-blocking):",fe)}x({name:"",profilePicture:null,dob:l,medications:"",marketingConsent:!1,allergies:"",instruments:[],bandName:"",email:"",phone:"",address:"",emergencyContacts:"",parentGuardianName:"",parentGuardianEmail:"",parentGuardianPhone:""}),v(null),await at()}catch(Ee){console.error("Failed to save student:",Ee);let fe=Ee?.message||"Unable to save student";fe.includes("CSRF")||fe.includes("csrf")||fe.includes("Security token")?fe="Session expired. Please refresh the page and try again.":(fe.includes("403")||fe.includes("Forbidden"))&&(fe="Access denied. Please refresh the page and try again."),alert(fe)}},_t=o=>{const g=o.student_id||o.id;if(!g)return;let z;if(o.dob)z=o.dob;else if(typeof o.age=="number"){const ee=new Date;ee.setFullYear(ee.getFullYear()-o.age),z=ee.toISOString().slice(0,10)}const Z=c(z),K=typeof Z=="number"&&Z<16;v(g),x({name:o.name||"",dob:z||l,medications:o.medications||"",marketingConsent:!!(o.marketing_consent??o.marketingConsent),allergies:o.allergies||"",instruments:o.instruments||[],bandName:o.band||"",email:o.email||"",phone:K?"":o.phone||"",address:o.address||"",emergencyContacts:o.emergency_contacts||o.emergencyContacts||o.emergency_contact||"",parentGuardianName:o.parent_name||"",parentGuardianEmail:o.parent_email||"",parentGuardianPhone:K?o.phone||"":o.parentGuardianPhone||o.parent_phone||""})},Ct=async o=>{if(o&&confirm("Are you sure you want to remove this student? This will delete their account, profile, and all associated data. This action cannot be undone."))try{await Je.remove(o),await at(),s({title:"Removed",description:"Student deleted successfully"})}catch(g){console.error(g),s({title:"Error",description:"Unable to remove student. Please try again.",variant:"destructive"})}},rt=async(o,g,z)=>{if(!o){s({title:"Error",description:"Missing user id"});return}V(o);try{const{apiFetch:Z}=await Y(async()=>{const{apiFetch:ee}=await import("./api-CyvozDRd.js");return{apiFetch:ee}},[]),K=await Z(`/api/admin/users/${o}/set-password`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({password:g})});if(!K.ok){const ee=await K.json().catch(()=>({}));throw new Error(ee.error||ee.message||"Failed to set password")}s({title:"Password updated",description:z||"New password applied"})}catch(Z){console.error(Z),s({title:"Error",description:Z?.message||"Unable to set password"})}finally{V(null)}},Le=()=>{const o=u.instruments||[];
36if(o.length>=3)return alert("Max 3 instruments");o.includes(y)||x(g=>({...g,instruments:[...g.instruments||[],y]}))},h=o=>x(g=>({...g,instruments:(g.instruments||[]).filter(z=>z!==o)})),q=c(u.dob),X=q!==void 0&&q<16,me=q!==void 0&&q>=65;return e.jsxs("div",{children:[e.jsx("div",{className:"mb-4 flex flex-col gap-2 sm:flex-row sm:items-center sm:justify-start"}),Fe,qe,e.jsxs("form",{onSubmit:kt,className:"grid gap-2",children:[e.jsx("input",{className:"h-10 rounded-md border px-3",placeholder:"Name",value:u.name||"",onChange:o=>x(g=>({...g,name:o.target.value}))}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-medium text-foreground/70",children:"Profile Picture (optional)"}),e.jsx("input",{type:"file",accept:"image/*",onChange:o=>{const g=o.target.files?.[0]||null;x(z=>({...z,profilePicture:g}))},className:"block w-full text-sm text-foreground file:mr-4 file:py-2 file:px-4 file:rounded-md file:border-0 file:text-sm file:font-semibold file:bg-primary file:text-primary-foreground hover:file:bg-primary/90"}),u.profilePicture&&e.jsxs("div",{className:"mt-2 flex items-center gap-2",children:[e.jsx("img",{src:URL.createObjectURL(u.profilePicture),alt:"Preview",className:"h-16 w-16 object-cover rounded-md border"}),e.jsx("span",{className:"text-sm text-foreground/70",children:u.profilePicture.name})]})]}),e.jsx("div",{className:"flex gap-2 flex-wrap",children:e.jsxs("label",{className:"flex flex-col",children:[e.jsx("span",{className:"text-sm text-foreground/70",children:"Date of birth"}),e.jsx("input",{type:"date",className:"h-10 rounded-md border px-3",value:u.dob||"",onChange:o=>x(g=>({...g,dob:o.target.value}))}),e.jsx("span",{className:"text-xs text-foreground/60 mt-1",children:q!==void 0?`${q} years`:"Age not set"})]})}),e.jsx("input",{className:"h-10 rounded-md border px-3",placeholder:"Emergency contact (required)",value:u.emergencyContacts||"",onChange:o=>x(g=>({...g,emergencyContacts:o.target.value}))}),e.jsx("input",{className:"h-10 rounded-md border px-3",placeholder:"Address (optional)",value:u.address||"",onChange:o=>x(g=>({...g,address:o.target.value}))}),e.jsxs("label",{className:"flex items-center gap-2",children:[e.jsx("input",{type:"checkbox",checked:!!u.marketingConsent,onChange:o=>x(g=>({...g,marketingConsent:o.target.checked}))}),e.jsx("span",{className:"text-sm",children:"Marketing consent"})]}),e.jsx("label",{className:"text-sm",children:"Allergies or similar issues (optional)"}),e.jsx("textarea",{className:"rounded-md border px-3 py-2",placeholder:"Allergies, intolerances or other relevant details",value:u.allergies||"",onChange:o=>x(g=>({...g,allergies:o.target.value}))}),e.jsx("label",{className:"text-sm",children:"Instrument(s) (max 3)"}),e.jsxs("div",{className:"flex gap-2 flex-wrap",children:[e.jsx("select",{className:"h-10 rounded-md border px-3 flex-1",value:y,onChange:o=>I(o.target.value),children:r.map(o=>e.jsx("option",{value:o,children:o},o))}),e.jsx("button",{type:"button",onClick:Le,className:"px-3 py-2 rounded-md border",children:"Add instrument"})]}),e.jsx("div",{className:"flex gap-2 flex-wrap",children:(u.instruments||[]).map(o=>e.jsxs("div",{className:"px-2 py-1 rounded-md border flex items-center gap-2",children:[e.jsx("div",{children:o}),e.jsx("button",{type:"button",onClick:()=>h(o),className:"px-2 py-1 rounded-md border",children:"x"})]},o))}),e.jsx("input",{className:"h-10 rounded-md border px-3",placeholder:"Band name (optional)",value:u.bandName||"",onChange:o=>x(g=>({...g,bandName:o.target.value}))}),X?e.jsxs(e.Fragment,{children:[e.jsx("input",{className:"h-10 rounded-md border px-3",placeholder:"Parent/Guardian name",value:u.parentGuardianName||"",onChange:o=>x(g=>({...g,parentGuardianName:o.target.value}))}),e.jsx("input",{className:"h-10 rounded-md border px-3",placeholder:"Parent/Guardian phone",value:u.parentGuardianPhone||"",onChange:o=>x(g=>({...g,parentGuardianPhone:o.target.value}))}),e.jsx("input",{className:"h-10 rounded-md border px-3",placeholder:"Parent/Guardian email",value:u.parentGuardianEmail||"",onChange:o=>x(g=>({...g,parentGuardianEmail:o.target.value}))})]}):e.jsxs(e.Fragment,{children:[e.jsx("input",{className:"h-10 rounded-md border px-3",placeholder:"Phone (optional)",value:u.phone||"",onChange:o=>x(g=>({...g,phone:o.target.value}))}),e.jsx("input",{className:"h-10 rounded-md border px-3",placeholder:"Email",value:u.email||"",onChange:o=>x(g=>({...g,email:o.target.value}))})]}),me&&e.jsxs(e.Fragment,{children:[e.jsx("label",{className:"text-sm",children:"Medications / medical info (optional)"}),e.jsx("textarea",{className:"rounded-md border px-3 py-2",placeholder:"Any medications or important medical information",value:u.medications||"",onChange:o=>x(g=>({...g,medications:o.target.value}))})]}),e.jsxs("div",{className:"flex flex-col gap-2 sm:flex-row",children:[e.jsx(w,{type:"submit",className:"w-full sm:w-auto",children:p?"Save":"Add"}),e.jsx(w,{type:"button",variant:"outline",className:"w-full sm:w-auto",onClick:()=>
36{x({name:"",profilePicture:null,dob:l,medications:"",marketingConsent:!1,allergies:"",instruments:[],bandName:"",email:"",phone:"",address:"",emergencyContacts:"",parentGuardianName:"",parentGuardianEmail:"",parentGuardianPhone:""}),v(null)},children:"Clear"})]})]}),e.jsxs("div",{className:"mt-4",children:[e.jsx("label",{htmlFor:"studentSearch",className:"mb-1 block text-sm font-medium text-foreground/80",children:"Search students"}),e.jsx("input",{id:"studentSearch",type:"search",placeholder:"Search by name, email, instrument...",value:L,onChange:o=>G(o.target.value),className:"h-10 w-full rounded-md border px-3 focus:border-primary focus:outline-none focus:ring-2 focus:ring-primary/20"})]}),e.jsxs("div",{className:"mt-4 grid gap-2",children:[n.length===0&&e.jsx("div",{className:"text-foreground/70",children:"No students yet."}),n.length>0&&ye.length===0&&Ce&&e.jsxs("div",{className:"rounded-md border border-dashed p-4 text-sm text-foreground/70",children:['No students match "',L.trim(),'".']}),ye.map(o=>{const g=o.student_id||o.id,z=o.user_id||o.userId||o.id,Z=g||z;o.email;const K=!!(Z&&A[Z]);return e.jsxs("div",{className:"flex flex-col gap-3 rounded-md border p-3",children:[e.jsx("div",{className:"space-y-2",children:e.jsxs("button",{type:"button",onClick:()=>st(Z),className:"flex w-full items-center justify-between gap-2 text-left",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[o.profile_picture_url?e.jsx("img",{src:o.profile_picture_url,alt:`${o.name}'s profile`,className:"h-12 w-12 rounded-full object-cover border"}):e.jsx("div",{className:"h-12 w-12 rounded-full bg-muted flex items-center justify-center border",children:e.jsx(We,{className:"h-6 w-6 text-muted-foreground"})}),e.jsxs("div",{children:[e.jsxs("span",{className:"font-medium",children:[o.name,o.age?` ⢠${o.age}`:"",o.isElderly?" ð´ Elderly":""]}),e.jsxs("div",{className:"text-sm text-foreground/70",children:[o.email||"No email",o.phone?` ⢠${o.phone}`:""]})]})]}),e.jsx(Zs,{className:`h-4 w-4 shrink-0 transition-transform ${K?"rotate-180":""}`})]})}),K&&e.jsxs("dl",{className:"grid gap-2 rounded-md bg-muted/40 p-3 text-sm sm:grid-cols-2",children:[o.address?e.jsxs("div",{children:[e.jsx("dt",{className:"font-medium text-foreground/80",children:"Address"}),e.jsx("dd",{children:o.address})]}):null,o.marketing_consent!==void 0||o.marketingConsent!==void 0?e.jsxs("div",{children:[e.jsx("dt",{className:"font-medium text-foreground/80",children:"Marketing consent"}),e.jsx("dd",{children:o.marketing_consent||o.marketingConsent?"Yes":"No"})]}):null,o.parent_name||o.parentGuardianName?e.jsxs("div",{children:[e.jsx("dt",{className:"font-medium text-foreground/80",children:"Guardian name"}),e.jsx("dd",{children:o.parent_name||o.parentGuardianName})]}):null,o.parent_email||o.parentGuardianEmail?e.jsxs("div",{children:[e.jsx("dt",{className:"font-medium text-foreground/80",children:"Guardian email"}),e.jsx("dd",{children:o.parent_email||o.parentGuardianEmail})]}):null,o.emergency_contacts?e.jsxs("div",{children:[e.jsx("dt",{className:"font-medium text-foreground/80",children:"Emergency contact"}),e.jsx("dd",{children:o.emergency_contacts})]}):null,o.phone?e.jsxs("div",{children:[e.jsx("dt",{className:"font-medium text-foreground/80",children:"Phone"}),e.jsx("dd",{children:o.phone})]}):null,o.allergies?e.jsxs("div",{children:[e.jsx("dt",{className:"font-medium text-foreground/80",children:"Allergies / issues"}),e.jsx("dd",{children:o.allergies})]}):null,o.medications?e.jsxs("div",{children:[e.jsx("dt",{className:"font-medium text-foreground/80",children:"Medications"}),e.jsx("dd",{children:o.medications})]}):null,o.instruments?e.jsxs("div",{children:[e.jsx("dt",{className:"font-medium text-foreground/80",children:"Instrument(s)"}),e.jsx("dd",{children:(()=>{try{if(Array.isArray(o.instruments))return o.instruments.join(", ");const ee=typeof o.instruments=="string"?JSON.parse(o.instruments):o.instruments;return Array.isArray(ee)?ee.join(", "):String(ee)}catch{return String(o.instruments)}})()})]}):null,o.band?e.jsxs("div",{children:[e.jsx("dt",{className:"font-medium text-foreground
36/80",children:"Band"}),e.jsx("dd",{children:o.band})]}):null,e.jsxs("div",{children:[e.jsx("dt",{className:"font-medium text-foreground/80",children:"Created"}),e.jsx("dd",{children:Be(o.created_at)})]}),e.jsxs("div",{children:[e.jsx("dt",{className:"font-medium text-foreground/80",children:"Last updated"}),e.jsx("dd",{children:Be(o.updated_at)})]})]}),e.jsxs("div",{className:"flex w-full flex-col gap-2 sm:w-auto sm:flex-row sm:flex-wrap sm:justify-end",children:[e.jsx(w,{type:"button",onClick:()=>_t(o),variant:"outline",size:"sm",className:"w-full whitespace-normal sm:w-auto",children:"Edit"}),e.jsx(w,{type:"button",onClick:()=>Ct(g),variant:"destructive",size:"sm",className:"w-full whitespace-normal sm:w-auto",children:"Remove"}),e.jsx(w,{type:"button",onClick:()=>rt(z,ir(),"Random password applied"),variant:"secondary",size:"sm",className:"w-full whitespace-normal sm:w-auto",disabled:U===z,children:U===z?"Working...":"Randomize password"}),e.jsx(w,{type:"button",onClick:()=>{const ee=window.prompt("Enter new password","");ee&&rt(z,ee,"Password updated")},variant:"outline",size:"sm",className:"w-full whitespace-normal sm:w-auto",disabled:U===z,children:"Set password"}),e.jsx(w,{type:"button",onClick:()=>{k(g||""),ne(!0)},variant:"outline",size:"sm",className:"w-full whitespace-normal sm:w-auto",children:"Upload material"}),e.jsx(w,{type:"button",onClick:async()=>{const ee=g||"";_e(ee),N(!0),pe(!0);try{const{apiFetch:ie}=await Y(async()=>{const{apiFetch:He}=await import("./api-CyvozDRd.js");return{apiFetch:He}},[]),de=await ie(`/api/admin/learning/${ee}`);le(Array.isArray(de)?de:de&&de.rows||[])}catch(ie){console.error(ie),s({title:"Failed to load resources",variant:"destructive"})}finally{pe(!1)}},variant:"outline",size:"sm",className:"w-full whitespace-normal sm:w-auto",children:"View resources"})]})]},Z)})]})]})}function xr({teachers:a,students:t}){const{toast:s}=Pe(),[r,n]=m.useState([]),[i,l]=m.useState(!0),[c,u]=m.useState(!1),[x,p]=m.useState(""),[v,y]=m.useState(""),[I,U]=m.useState(!1),[V,L]=m.useState(""),[G,W]=m.useState(""),ne=r.filter(b=>{if(!G.trim())return!0;const F=G.toLowerCase(),T=b.teacher_name?.toLowerCase()||"",R=b.student_name?.toLowerCase()||"",M=b.teacher_email?.toLowerCase()||"",A=b.student_email?.toLowerCase()||"";return T.includes(F)||R.includes(F)||M.includes(F)||A.includes(F)}),E=async()=>{try{l(!0),console.log("ð [Admin] Fetching teacher-student assignments...");const{apiFetch:b}=await Y(async()=>{const{apiFetch:T}=await import("./api-CyvozDRd.js");return{apiFetch:T}},[]),F=await b("/api/admin/teacher-students");console.log("â [Admin] Assignments loaded:",F?.length||0),console.log("ð [Admin] Assignment IDs:",F?.map(T=>T.id)||[]),n(Array.isArray(F)?[...F]:[])}catch(b){console.error("â [Admin] Failed to load assignments:",{error:b.message,status:b.status,response:b.response}),n([]),s({title:"Error loading assignments",description:b?.message||"Failed to load teacher-student assignments",variant:"destructive"})}finally{l(!1)}};m.useEffect(()=>{E()},[]);const d=async()=>{console.log(` 37ââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââ`),console.log("â [Teacher Assignment] STARTING ASSIGNMENT PROCESS"),console.log(`ââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââ 38`);const b=a.find(M=>M.id===x),F=t.find(M=>M.id===v);if(console.log("ð [Admin] Selected objects:",{selectedTeacher:x,selectedStudent:v,teacherObj:b?{id:b.id,name:b.name,role:b.role}:null,studentObj:F?{id:F.id,name:F.name}:null}),!b||!F){s({title:"Invalid selection",description:b?"Selected student not found. Please refresh the page.":"Selected teacher not found. Please refresh the page.",variant:"destructive"});return}const T=b.id,R=F.id;if(!T||!R){s({title:"Missing information",description:"Please select both a teacher and student",variant:"destructive"});return}try{console.log("ð [Teacher Assignment] Creating assignment:",{teacher:`${b.name} (${T})`,student:`${F.name} (${R}
38)`,isPrimary:I?"YES - Primary Teacher":"No",notes:V||"(none)"});const{apiFetch:M}=await Y(async()=>{const{apiFetch:te}=await import("./api-CyvozDRd.js");return{apiFetch:te}},[]),A=await M("/api/admin/teacher-students",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({teacherId:T,studentId:R,isPrimary:I,notes:V})});console.log("â [Teacher Assignment] SUCCESS - Assignment created:",{assignmentId:A.id,teacher:b.name,student:F.name,isPrimary:I,result:A}),console.log(` 39ââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââ`),u(!1),p(""),y(""),U(!1),L(""),await E(),s({title:"Success",description:"Student assigned to teacher successfully"})}catch(M){let A=M?.details||M?.message||"Failed to assign student to teacher. Please check the console for details.";A.includes("Teacher not found")?A+=" (Check that the teacher exists and is not deleted.)":A.includes("Student not found")&&(A+=" (Check that the student exists and is not deleted.)"),console.error(` 40âââ [Teacher Assignment] FAILED âââ`),console.error("Teacher:",b?.name,`(${T})`),console.error("Student:",F?.name,`(${R})`),console.error("Error details:",{message:M?.message,status:M?.status,details:M?.details,fullError:M}),console.error(`ââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââ 41`),s({title:"Assignment failed",description:A,variant:"destructive"})}},C=async b=>{const F=r.find(T=>T.id===b);if(console.log(` 42ââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââ`),console.log("â [Teacher Unassignment] STARTING REMOVAL PROCESS"),console.log("Assignment to remove:",{id:b,teacher:F?.teacher_name||"Unknown",student:F?.student_name||"Unknown",isPrimary:F?.is_primary?"YES - Primary":"No"}),console.log(`ââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââ 43`),!confirm("Are you sure you want to unassign this student from the teacher?")){console.log("ð« [Teacher Unassignment] Cancelled by user");return}try{console.log("ðï¸ [Teacher Unassignment] Sending DELETE request for ID:",b);const{apiFetch:T}=await Y(async()=>{const{apiFetch:R}=await import("./api-CyvozDRd.js");return{apiFetch:R}},[]);await T(`/api/admin/teacher-students/${b}`,{method:"DELETE"}),console.log("â [Teacher Unassignment] SUCCESS - Assignment removed:",b),console.log(`ââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââ 44`),await E(),s({title:"Success",description:"Student unassigned from teacher"})}catch(T){console.error(` 45â [Teacher Unassignment] FAILED:`,T),T?.message?.includes("Not found")||T?.message?.includes("404")?(console.warn("â ï¸ [Teacher Unassignment] Assignment ID not found in database:",b),console.warn("This usually means the ID in frontend state doesn't match database."),console.log("ð Refreshing assignment list to sync with database..."),await E(),s({title:"Info",description:"Assignment already removed. List refreshed.",variant:"default"})):(console.error("â [Teacher Unassignment] Unexpected error:",{message:T?.message,details:T?.details,fullError:T}),alert(T?.message||"Failed to unassign student from teacher")),console.error(`ââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââ 46`)}},k=async(b,F)=>{const T=a.find(M=>M.id===b),R=t.find(M=>M.id===F);console.log(` 47ââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââ`),console.log("â [Primary Teacher] SETTING PRIMARY TEACHER"),console.log(`ââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââ 48`);try{console.log("ð¯ [Primary Teacher] Request details:",{teacher:T?.name||"Unknown",teacherId:b,student:R?.name||"Unknown",studentId:F});const{apiFetch:M}=await Y(async()=>{const{apiFetch:A}=await import("./api-CyvozDRd.js");return{apiFetch:A}},[]);await M(`/api/admin/students/${F}/set-primary-teacher`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({teacherId:b})}),console.log("â [Primary Teacher] SUCCESS - Primary teacher set"),console.log("Teacher:",T?.name,"is now the primary teacher for",R?.name),console.log(`ââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââ 49`),await E(),s({title:"Success",description:"Primary teacher updated successfully"})}catch(M){console.error(` 50âââ [Primary Teacher] FAILED âââ`),console.error("Teacher:",T?.name,`(${b})`),console.error("Student:",R?.name,`(${F})`),console.error("Error details:",{message:M.message,details:M.details,fullError:M}
50),console.error(`ââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââ 51`),s({title:"Update failed",description:M?.details||M?.message||"Failed to set primary teacher. Please check the console for details.",variant:"destructive"})}};return i?e.jsx("div",{className:"text-sm text-foreground/70",children:"Loading assignments..."}):e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex gap-3 items-center",children:[e.jsxs("div",{className:"flex-1 relative",children:[e.jsx(qs,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-foreground/40"}),e.jsx(Ms,{placeholder:"Search by teacher or student name...",value:G,onChange:b=>W(b.target.value),className:"pl-9 pr-9"}),G&&e.jsx("button",{onClick:()=>W(""),className:"absolute right-3 top-1/2 -translate-y-1/2 text-foreground/40 hover:text-foreground",children:e.jsx(Me,{className:"h-4 w-4"})})]}),e.jsx(w,{onClick:()=>u(!0),children:"Assign Student to Teacher"})]}),e.jsx("div",{className:"flex justify-between items-center",children:e.jsx("div",{className:"text-sm text-foreground/70",children:G?e.jsxs(e.Fragment,{children:["Showing ",ne.length," of ",r.length," assignment",r.length!==1?"s":""]}):e.jsxs(e.Fragment,{children:[r.length," assignment",r.length!==1?"s":""]})})}),ne.length===0?e.jsx("div",{className:"text-center py-8 text-foreground/60",children:G?e.jsxs(e.Fragment,{children:['No assignments found matching "',G,'".',e.jsx("button",{onClick:()=>W(""),className:"ml-2 text-primary hover:underline",children:"Clear search"})]}):"No teacher-student assignments yet. Click 'Assign Student to Teacher' to get started."}):e.jsx("div",{className:"grid gap-3",children:ne.map(b=>e.jsxs("div",{className:"border rounded-lg p-4",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-4",children:[e.jsxs("div",{children:[e.jsxs("div",{className:"font-medium",children:[b.student_name,b.is_primary&&e.jsx("span",{className:"ml-2 px-2 py-1 text-xs bg-primary text-primary-foreground rounded",children:"Primary"})]}),e.jsxs("div",{className:"text-sm text-foreground/70",children:["Student ⢠",b.student_email]})]}),e.jsx("div",{className:"text-foreground/40",children:"â"}),e.jsxs("div",{children:[e.jsx("div",{className:"font-medium",children:b.teacher_name}),e.jsxs("div",{className:"text-sm text-foreground/70",children:["Teacher ⢠",b.teacher_email]})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[!b.is_primary&&e.jsx(w,{size:"sm",variant:"outline",onClick:()=>k(b.teacher_id,b.student_id),children:"Set as Primary"}),e.jsx(w,{size:"sm",variant:"destructive",onClick:()=>C(b.id),children:"Unassign"})]})]}),b.notes&&e.jsxs("div",{className:"mt-2 text-sm text-foreground/70",children:[e.jsx("strong",{children:"Notes:"})," ",b.notes]}),e.jsxs("div",{className:"mt-2 text-xs text-foreground/50",children:["Assigned ",new Date(b.assigned_at).toLocaleDateString()]})]},b.id))}),c&&e.jsx("div",{className:"fixed inset-0 z-50 flex items-center justify-center bg-black/50 p-4",children:e.jsxs("div",{className:"w-full max-w-md rounded-lg bg-card p-6 shadow-xl",children:[e.jsx("h3",{className:"text-lg font-semibold mb-4",children:"Assign Student to Teacher"}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-medium mb-2",children:"Teacher"}),e.jsxs("select",{className:"w-full h-10 rounded-md border px-3",value:x,onChange:b=>p(b.target.value),children:[e.jsx("option",{value:"",children:"Select a teacher"}),a.map(b=>e.jsxs("option",{value:b.id,children:[b.name," (",b.email,")"]},b.id))]})]}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-medium mb-2",children:"Student"}),e.jsxs("select",{className:"w-full h-10 rounded-md border px-3",value:v,onChange:b=>y(b.target.value),children:[e.jsx("option",{value:"",children:"Select a student"}),t.map(b=>e.jsxs("option",{value:b.student_id,children:[b.name," (",b.email,")"]},b.student_id))]})]}),e.jsx("div",{children:e.jsxs("label",{className:"flex items-center gap-2",children:[e.jsx("input",{type:"checkbox",checked:I,onChange:b=>U(b.target.checked)}),e.jsx("span",{className:"text-sm",children:"Set as primary teacher"})]})}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-medium mb-2",children:"Notes (optional)"}),e.jsx("textarea",{className:"w-full rounded-md border px-3 py-2",rows:3,value:V,onChange:b=>L(b.target.value),placeholder:"Any additional notes about this assignment"})]}),e.jsxs("div",{className:"flex gap-2 justify-end",children:[e.jsx(w,{variant:"outline",onClick:()=>{u(!1),p(""),y(""),U(!1),L("")},children:"Cancel"}),e.jsx(w,{onClick:d,children:"Assign"})]})]})]})})]})}export{Mr as default};
Line numbers count LF bytes from the start of the resource, as the search results do. Vendor segments are library code the classifier recognised; they are stored but not indexed. Bytes are shown as Latin1 characters, one per byte.