PageSourceSearch

https://apparglobal.com/_next/static/chunks/4859.3d46b614b48786a8.js

js apparglobal.com collected 2026-10-04 04:58:21 UTC 438,332 bytes, 1 lines download raw bytes

1"use strict";(self.webpackChunk_N_E=self.webpackChunk_N_E||[]).push([[4859],{27142:(e,t,r)=>{r.d(t,{GN:()=>m,K$:()=>h,LB:()=>u,RM:()=>c,UG:()=>i,dT:()=>d,e6:()=>o,nc:()=>l});var n=r(22454),a=r(37942);async function s(e){let{data:t,error:r}=await a.N.from("products").select("*").eq("slug",e).maybeSingle();if(r)throw r;return t}function i(e,t){var r,n;if(!t)return e;let a=Array.isArray(t.gallery_images)?t.gallery_images.filter(Boolean):[];return{...e,...t.title&&{title:t.title},...t.image&&{image:t.image},...t.description&&{description:t.description},...t.short_description&&{shortDescription:t.short_description},...a.length>0&&{galleryImages:a},...t.price_range&&{pricing:[t.price_range,...(e.pricing||[]).slice(1)]},...t.moq&&{moq:t.moq},...t.sku&&{sku:t.sku},...t.stock_status&&{stockStatus:t.stock_status},is_featured:null!=(n=null!=(r=t.is_featured)?r:e.is_featured)&&n}}function l(e){return(0,n.I)({queryKey:["public","product_override",e],queryFn:()=>s(e),staleTime:3e5,gcTime:18e5,retry:1,enabled:!!e})}async function o(e,t){let{error:r}=await a.N.from("products").upsert({slug:e,...t,updated_at:new Date().toISOString()},{onConflict:"slug"});if(r)throw r}async function d(e){let{data:t,error:r}=await a.N.from("products").select("*").eq("slug",e).maybeSingle();if(r)throw r;return t}async function c(e){let{data:t,error:r}=await a.N.from("product_tag_assignments").select("tag_id").eq("product_slug",e);if(r)throw r;return(t||[]).map(e=>e.tag_id)}async function u(e,t){let{error:r}=await a.N.from("product_tag_assignments").delete().eq("product_slug",e);if(r)throw r;if(!(null==t?void 0:t.length))return;let n=t.map(t=>({product_slug:e,tag_id:t})),{error:s}=await a.N.from("product_tag_assignments").insert(n);if(s)throw s}async function m(e){let{data:t,error:r}=await a.N.from("product_brand_assignments").select("brand_id").eq("product_slug",e);if(r)throw r;return(t||[]).map(e=>e.brand_id)}async function h(e,t){let{error:r}=await a.N.from("product_brand_assignments").delete().eq("product_slug",e);if(r)throw r;if(!(null==t?void 0:t.length))return;let n=t.map(t=>({product_slug:e,brand_id:t})),{error:s}=await a.N.from("product_brand_assignments").insert(n);if(s)throw s}},37942:(e,t,r)=>{r.d(t,{N:()=>i,z:()=>l});var n=r(6942);let a="https://ooysllobixfyzkgksboh.supabase.co",s="eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJzdXBhYmFzZSIsInJlZiI6Im9veXNsbG9iaXhmeXprZ2tzYm9oIiwicm9sZSI6ImFub24iLCJpYXQiOjE3NzQ1NjczMjUsImV4cCI6MjA5MDE0MzMyNX0.gXq03AsLxNfqCEfr9pkVjq_2HkiUTLFmBea6zChnhkg";if(!a||!s)throw Error("Missing VITE_SUPABASE_URL or VITE_SUPABASE_ANON_KEY in env.");let i=(0,n.UU)(a,s);function l(e){return e?[e.message,e.details,e.hint].filter(Boolean).join(" — "):""}},94859:(e,t,r)=>{r.r(t),r.d(t,{default:()=>sB});var n=r(95155),a=r(12115),s=r(62335),i=r(51876),l=r(31461),o=r(99776);let d={ADD_TOAST:"ADD_TOAST",UPDATE_TOAST:"UPDATE_TOAST",DISMISS_TOAST:"DISMISS_TOAST",REMOVE_TOAST:"REMOVE_TOAST"},c=0,u=new Map,m=e=>{if(u.has(e))return;let t=setTimeout(()=>{u.delete(e),x({type:d.REMOVE_TOAST,toastId:e})},400);u.set(e,t)};function h(e){let t="auto-".concat(e),r=u.get(t);r&&(clearTimeout(r),u.delete(t))}let p=[],g={toasts:[]};function x(e){g=((e,t)=>{switch(t.type){case d.ADD_TOAST:return{...e,toasts:[t.toast,...e.toasts].slice(0,20)};case d.UPDATE_TOAST:return{...e,toasts:e.toasts.map(e=>e.id===t.toast.id?{...e,...t.toast}:e)};case d.DISMISS_TOAST:{let{toastId:r}=t;return r?(h(r),m(r)):e.toasts.forEach(e=>{h(e.id),m(e.id)}),{...e,toasts:e.toasts.map(e=>e.id===r||void 0===r?{...e,open:!1}:e)}}case d.REMOVE_TOAST:if(void 0===t.toastId)return{...e,toasts:[]};return{...e,toasts:e.toasts.filter(e=>e.id!==t.toastId)}}})(g,e),p.forEach(e=>{e(g)})}function f(){let{duration:e,...t}=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},r=(c=(c+1)%Number.MAX_VALUE).toString(),n=void 0===e?5500:Number(e),a=()=>x({type:d.DISMISS_TOAST,toastId:r});if(x({type:d.ADD_TOAST,toast:{...t,id:r,open:!0,onOpenChange:e=>{e||a()}}}),Number.isFinite(n)&&n>0){let e=setTimeout(()=>a(),n);u.set("auto-".concat(r),e)}return{id:r,dismiss:a,update:e=>x({type:d.UPDATE_TOAST,toast:{...e,id:r}})}}var v=r(83101),y=r(26615),b=r(13672);let j=a.forwardRef((e,t)=>
1{let{...r}=e;return(0,n.jsx)("div",{ref:t,className:"fixed top-0 z-[100] flex max-h-screen w-full flex-col-reverse p-4 sm:bottom-0 sm:right-0 sm:top-auto sm:flex-col md:max-w-[420px]",...r})});j.displayName="ToastProvider";let w=a.forwardRef((e,t)=>{let{...r}=e;return(0,n.jsx)("div",{ref:t,className:"fixed top-0 z-[100] flex max-h-screen w-full flex-col-reverse p-4 sm:bottom-0 sm:right-0 sm:top-auto sm:flex-col md:max-w-[420px]",...r})});w.displayName="ToastViewport";let _=(0,v.F)("group pointer-events-auto relative flex w-full items-center justify-between space-x-4 overflow-hidden rounded-md border p-6 pr-8 shadow-lg transition-all data-[swipe=cancel]:translate-x-0 data-[swipe=end]:translate-x-[var(--radix-toast-swipe-end-x)] data-[swipe=move]:translate-x-[var(--radix-toast-swipe-move-x)] data-[swipe=move]:transition-none data-[state=open]:animate-in data-[state=closed]:animate-out data-[swipe=end]:animate-out data-[state=closed]:fade-out-80 data-[state=closed]:slide-out-to-right-full data-[state=open]:slide-in-from-top-full data-[state=open]:sm:slide-in-from-bottom-full",{variants:{variant:{default:"border bg-background text-foreground",destructive:"destructive group border-destructive bg-destructive text-destructive-foreground"}},defaultVariants:{variant:"default"}}),N=a.forwardRef((e,t)=>{let{className:r,variant:a,open:s=!0,onOpenChange:i,...l}=e;return(0,n.jsx)("div",{ref:t,"data-state":s?"open":"closed",className:(0,b.cn)(_({variant:a}),r),...l})});N.displayName="Toast",a.forwardRef((e,t)=>{let{className:r,...a}=e;return(0,n.jsx)("div",{ref:t,className:(0,b.cn)("inline-flex h-8 shrink-0 items-center justify-center rounded-md border bg-transparent px-3 text-sm font-medium ring-offset-background transition-colors hover:bg-secondary focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2 disabled:pointer-events-none disabled:opacity-50 group-[.destructive]:border-muted/40 group-[.destructive]:hover:border-destructive/30 group-[.destructive]:hover:bg-destructive group-[.destructive]:hover:text-destructive-foreground group-[.destructive]:focus:ring-destructive",r),...a})}).displayName="ToastAction";let k=a.forwardRef((e,t)=>{let{className:r,...a}=e;return(0,n.jsxs)("button",{type:"button",ref:t,className:(0,b.cn)("absolute right-2 top-2 rounded-md p-1 text-foreground/60 opacity-90 transition-opacity hover:text-foreground hover:opacity-100 focus:opacity-100 focus:outline-none focus:ring-2 group-[.destructive]:text-red-300 group-[.destructive]:hover:text-red-50 group-[.destructive]:focus:ring-red-400 group-[.destructive]:focus:ring-offset-red-600",r),...a,children:[(0,n.jsx)(y.A,{className:"h-4 w-4","aria-hidden":!0}),(0,n.jsx)("span",{className:"sr-only",children:"Close"})]})});k.displayName="ToastClose";let S=a.forwardRef((e,t)=>{let{className:r,...a}=e;return(0,n.jsx)("div",{ref:t,className:(0,b.cn)("text-sm font-semibold",r),...a})});S.displayName="ToastTitle";let C=a.forwardRef((e,t)=>{let{className:r,...a}=e;return(0,n.jsx)("div",{ref:t,className:(0,b.cn)("text-sm opacity-90",r),...a})});function A(){let{toasts:e}=function(){let[e,t]=(0,a.useState)(g);return(0,a.useEffect)(()=>(p.push(t),()=>{let e=p.indexOf(t);e>-1&&p.splice(e,1)}),[]),{...e,toast:f,dismiss:e=>x({type:d.DISMISS_TOAST,toastId:e})}}();return(0,n.jsxs)(j,{children:[e.map(function(e){let{id:t,title:r,description:a,action:s,open:i,onOpenChange:l,...o}=e;return(0,n.jsxs)(N,{open:i,onOpenChange:l,...o,children:[(0,n.jsxs)("div",{className:"grid gap-1",children:[r&&(0,n.jsx)(S,{children:r}),a&&(0,n.jsx)(C,{children:a})]}),s,(0,n.jsx)(k,{onClick:()=>null==l?void 0:l(!1)})]},t)}),(0,n.jsx)(w,{})]})}C.displayName="ToastDescription";var E=r(18720),T=r(37942);let q=(0,a.createContext)();async function M(e){if(!e)return null;try{var t,r;let n,a=await (n=T.N.from("user_roles").select("role").eq("id",e).maybeSingle(),Promise.race([n,new Promise((e,t)=>setTimeout(()=>t(Error("timeout")),4e3))]));if(null==a?void 0:a.error)return console.error("Error fetching user role:",a.error),null;return null!=(r=null==a||null==(t=a.data)?void 0:t.role)?r:null}catch(e){return null}}let P=e=>{let{children:t}=e,[r,s]=(0,a.useState)(null),[i,l]=(0,a.useState)(null),[o,d]=(0,a.useState)(null),[c,u]=(0,a.useState)(!0),[m,h]=(0,a.useState)(null),p=(0,a.useRef)(null),g=!!r,x="admin"===o,f=(0,a.useCallback)(async e=>{var t;if(!(null==e?void 0:e.id))return p.current=null,d(null),null;if((null==(t=p.current)?void 0:t.userId)===e.id)return p.current.promise;let r=M(e.id).then(e=>{var t;return(null==(t=p.current)?void 0:t.promise)===r&&(p.current=null),d(e),e});return p.current={userId:e.id,promise:r},r},[]),v=(0,a.useCallback)(async e=>{try{var t;let r=null!=(t=null==e?void 0:e.user)?t:null;if(!r){h(null),p.current=null,d(null);return}let n=await f(r);h("admin"!==n?{type:"not_admin"}:null)}catch(e){h({type:"auth_check_failed"})}},[f]);(0,a.useEffect)(()=>{let e=!0,t=!1;(async()=>{u(!0);try{var r,n;let{data:a}=await T.N.auth.getSession();if(!e)return;let i=null!=(r=a.session)?r:null;l(i),s(null!=(n=null==i?void 0:i.user)?n:null),t=!0,v(i)}finally{e&&u(!1)}})();let{data:r}=T.N.auth.onAuthStateChange(async(r,n)=>{var a;e&&(l(null!=n?n:null),s(null!=(a=null==n?void 0:n.user)?a:null),u(!1),"INITIAL_SESSION"===r&&t||v(null!=n?n:null))});return()=>{var t,n;e=!1,null==(n=r.subscription)||null==(t=n.unsubscribe)||t.call(n)}},[v]);let y=(0,a.useCallback)(async function(){let{next:e}=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},t="".concat(window.location.origin).concat(e||"/admin"),{data:r,error:n}=await T.N.auth.signInWithOAuth({provider:"google",options:{redirectTo:t}});if(n)throw n;return r},[]),b=(0,a.useCallback)(async()=>{await T.N.auth.signOut()},[]),j=(0,a.useMemo)(()=>({user:r,session:i,role:o,isAdmin:x,isAuthenticated:g,isLoadingAuth:c,isLoadingPublicSettings:!1,authError:m,appPublicSettings:null,loginWithGoogle:y,logout:b}),[r,i,o,x,g,c,m,y,b]);return(0,n.jsx)(q.Provider,{value:j,children:t})},I=()=>{let e=(0,a.useContext)(q);
1if(!e)throw Error("useAuth must be used within an AuthProvider");return e};var L=r(88793);function O(e){let{children:t}=e,{isLoadingAuth:r,isAuthenticated:a,isAdmin:i,logout:l,user:o,role:d}=I(),c=(0,s.zy)();if(r)return(0,n.jsx)("div",{className:"fixed inset-0 flex items-center justify-center",children:(0,n.jsx)("div",{className:"w-8 h-8 border-4 border-slate-200 border-t-slate-800 rounded-full animate-spin"})});if(!a){let e=encodeURIComponent(c.pathname+c.search);return(0,n.jsx)(s.C5,{to:"/login/?next=".concat(e),replace:!0})}return i?t:(0,n.jsx)("div",{className:"min-h-[60vh] flex items-center justify-center px-6",children:(0,n.jsxs)("div",{className:"w-full max-w-md rounded-2xl border bg-card p-6",children:[(0,n.jsx)("h1",{className:"text-xl font-semibold",children:"Admin access required"}),(0,n.jsxs)("p",{className:"text-sm text-muted-foreground mt-2",children:["You are signed in as ",(0,n.jsx)("span",{className:"font-medium",children:(null==o?void 0:o.email)||"this account"}),d?" (".concat(d,")"):"",", but this account is not authorized for the admin panel."]}),(0,n.jsxs)("div",{className:"mt-5 flex gap-2",children:[(0,n.jsx)(L.Button,{type:"button",variant:"outline",onClick:()=>l(),children:"Sign out"}),(0,n.jsx)(L.Button,{type:"button",onClick:()=>window.location.href="/login/",children:"Try another account"})]})]})})}var R=r(16802),D=r(6943),B=r(93790),F=r(91719),U=r(59007),z=r(5225),K=r(16455),G=r(19201),W=r(5468),H=r(98428),V=r(57259);let Q=V.bL,Y=V.R6,J=V.Ke;var $=r(7870);let X=a.forwardRef((e,t)=>{let{className:r,...a}=e;return(0,n.jsx)($.bL,{ref:t,className:(0,b.cn)("relative flex h-10 w-10 shrink-0 overflow-hidden rounded-full",r),...a})});X.displayName=$.bL.displayName;let Z=a.forwardRef((e,t)=>{let{className:r,...a}=e;return(0,n.jsx)($._V,{ref:t,className:(0,b.cn)("aspect-square h-full w-full",r),...a})});Z.displayName=$._V.displayName;let ee=a.forwardRef((e,t)=>{let{className:r,...a}=e;return(0,n.jsx)($.H4,{ref:t,className:(0,b.cn)("flex h-full w-full items-center justify-center rounded-full bg-muted",r),...a})});ee.displayName=$.H4.displayName;var et=r(35646);let er=et.bL;et.l9;let en=et.ZL,ea=a.forwardRef((e,t)=>{let{className:r,...a}=e;return(0,n.jsx)(et.hJ,{className:(0,b.cn)("fixed inset-0 z-50 bg-black/80 data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0",r),...a,ref:t})});ea.displayName=et.hJ.displayName;let es=a.forwardRef((e,t)=>{let{className:r,...a}=e;return(0,n.jsxs)(en,{children:[(0,n.jsx)(ea,{}),(0,n.jsx)(et.UC,{ref:t,className:(0,b.cn)("fixed left-[50%] top-[50%] z-50 grid w-full max-w-lg translate-x-[-50%] translate-y-[-50%] gap-4 border bg-background p-6 shadow-lg duration-200 data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[state=closed]:slide-out-to-left-1/2 data-[state=closed]:slide-out-to-top-[48%] data-[state=open]:slide-in-from-left-1/2 data-[state=open]:slide-in-from-top-[48%] sm:rounded-lg",r),...a})]})});es.displayName=et.UC.displayName;let ei=e=>{let{className:t,...r}=e;return(0,n.jsx)("div",{className:(0,b.cn)("flex flex-col space-y-2 text-center sm:text-left",t),...r})};ei.displayName="AlertDialogHeader";let el=e=>{let{className:t,...r}=e;return(0,n.jsx)("div",{className:(0,b.cn)("flex flex-col-reverse sm:flex-row sm:justify-end sm:space-x-2",t),...r})};el.displayName="AlertDialogFooter";let eo=a.forwardRef((e,t)=>{let{className:r,...a}=e;return(0,n.jsx)(et.hE,{ref:t,className:(0,b.cn)("text-lg font-semibold",r),...a})});eo.displayName=et.hE.displayName;let ed=a.forwardRef((e,t)=>{let{className:r,...a}=e;return(0,n.jsx)(et.VY,{ref:t,className:(0,b.cn)("text-sm text-muted-foreground",r),...a})});ed.displayName=et.VY.displayName;let ec=a.forwardRef((e,t)=>{let{className:r,...a}=e;return(0,n.jsx)(et.rc,{ref:t,className:(0,b.cn)((0,L.r)(),r),...a})});ec.displayName=et.rc.displayName;let eu=a.forwardRef((e,t)=>{let{className:r,...a}=e;return(0,n.jsx)(et.ZD,{ref:t,className:(0,b.cn)((0,L.r)({variant:"outline"}),"mt-2 sm:mt-0",r),...a})});eu.displayName=et.ZD.displayName;let em=(0,a.createContext)(null);function eh(e){var t,r;let{children:l}=e,o=(0,a.useRef)({isDirty:!1,variant:"settings",onSave:async()=>{},onDiscard:()=>{}}),d=(0,a.useCallback)(e=>
1{if(!e){o.current={isDirty:!1,variant:"settings",onSave:async()=>{},onDiscard:()=>{}};return}o.current=e},[]),c=(0,a.useMemo)(()=>({register:d}),[d]),u=(0,s.KP)((0,a.useCallback)(e=>{var t;let{currentLocation:r,nextLocation:n}=e;return(r.pathname!==n.pathname||r.search!==n.search)&&!!(null==(t=o.current)?void 0:t.isDirty)},[]));(0,i.K)((0,a.useCallback)(e=>{var t;(null==(t=o.current)?void 0:t.isDirty)&&(e.preventDefault(),e.returnValue="")},[]));let m=()=>{"blocked"===u.state&&u.reset()},h=async e=>{if("blocked"===u.state)try{let t=await (null==e?void 0:e());if(!1===t)return;u.proceed()}catch(e){"blocked"===u.state&&u.reset()}},p=()=>{if("blocked"===u.state)try{var e,t;null==(t=o.current)||null==(e=t.onDiscard)||e.call(t)}finally{u.proceed()}},g="blocked"===u.state,x=null!=(r=null==(t=o.current)?void 0:t.variant)?r:"settings";return(0,n.jsxs)(em.Provider,{value:c,children:[l,(0,n.jsx)(er,{open:g,onOpenChange:e=>{e||m()},children:(0,n.jsxs)(es,{className:"max-w-md",children:[(0,n.jsxs)(ei,{children:[(0,n.jsx)(eo,{children:"Unsaved changes"}),(0,n.jsx)(ed,{children:"blog"===x?"You have unsaved edits to this post. Save, save as draft, discard changes, or stay on this page.":"You have unsaved settings. Save them, discard changes, or stay on this page."})]}),(0,n.jsx)(el,{className:"flex-col gap-2 sm:flex-col sm:space-x-0",children:"blog"===x?(0,n.jsxs)(n.Fragment,{children:[(0,n.jsxs)("div",{className:"flex flex-col sm:flex-row flex-wrap gap-2 w-full justify-end",children:[(0,n.jsx)(L.Button,{type:"button",variant:"default",onClick:()=>h(()=>{var e,t;return null==(t=o.current)||null==(e=t.onSave)?void 0:e.call(t)}),children:"Save"}),(0,n.jsx)(L.Button,{type:"button",variant:"secondary",onClick:()=>h(()=>{var e,t;return null==(t=o.current)||null==(e=t.onSaveDraft)?void 0:e.call(t)}),children:"Save as draft"}),(0,n.jsx)(L.Button,{type:"button",variant:"destructive",onClick:p,children:"Discard"})]}),(0,n.jsx)(eu,{className:"w-full sm:w-auto mt-0",onClick:m,children:"Stay on page"})]}):(0,n.jsxs)(n.Fragment,{children:[(0,n.jsxs)("div",{className:"flex flex-col sm:flex-row gap-2 w-full justify-end",children:[(0,n.jsx)(L.Button,{type:"button",onClick:()=>h(()=>{var e,t;return null==(t=o.current)||null==(e=t.onSave)?void 0:e.call(t)}),children:"Save"}),(0,n.jsx)(L.Button,{type:"button",variant:"destructive",onClick:p,children:"Discard"})]}),(0,n.jsx)(eu,{className:"w-full sm:w-auto mt-0",onClick:m,children:"Stay on page"})]})})]})})]})}function ep(e){let{register:t}=(0,a.useContext)(em)||{};(0,a.useEffect)(()=>{if(t)return t(e),()=>t(null)},[t,e.isDirty,e.variant,e.onSave,e.onSaveDraft,e.onDiscard])}let eg=[{label:"Dashboard",icon:R.A,path:"/admin/"}],ex=[{label:"Overview",path:"/admin/seo/overview/"},{label:"Auto Linking",path:"/admin/auto-linking/"},{label:"Verification & GA4",path:"/admin/seo/verification/"},{label:"Redirects",path:"/admin/seo/redirects/"}],ef=[{label:"Users",icon:D.A,path:"/admin/users/"}],ev=[{label:"All Posts",path:"/admin/blog/"},{label:"Add Post",path:"/admin/blog/new/"},{label:"Categories",path:"/admin/blog/categories/"}],ey=[{label:"General",path:"/admin/settings/general/",key:"general"},{label:"API Settings",path:"/admin/api-settings/",key:"api-settings"}],eb=[{label:"All Products",path:"/admin/products/",key:"list"},{label:"Add new",path:"/admin/products/new/",key:"new"},{label:"Brands",path:"/admin/products/brands/",key:"brands"},{label:"Categories",path:"/admin/products/categories/",key:"categories"},{label:"Tags",path:"/admin/products/tags/",key:"tags"},{label:"Reviews",path:"/admin/products/reviews/",key:"reviews"}];var ej=r(3961),ew=r(2421),e_=r(62593),eN=r(94915),ek=r(80366),eS=r(99628);let eC="cms-uploads",eA="media";function eE(e){return String(e||"webp").replace(/^\./,"").toLowerCase()||"webp"}function eT(e){let t=eE(e);return"".concat(eA,"/").concat(crypto.randomUUID(),".").concat(t)}function eq(e,t){let r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:eA,n=String(r||"").replace(/^\/+|\/+$/g,"")||eA,a=function(e){let t=String(e||"").trim();return t&&((t.split(/[/\\]/).pop()||t).replace(/\.[^/.]+$/,"")||"upload").normalize("NFKD").replace(/[\u0300-\u036f]/g,"").replace(/[^a-zA-Z0-9._-]+/g,"-").replace(/-+/g,"-").replace(/^[-.]+|[-.]+$/g,"")||"upload"}(e),s=eE(t);return"".concat(n,"/").concat(a,".").concat(s)}let eM=/\.(jpe?g|png|gif|webp|svg)$/i;async function eP(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:T.N,{maxFiles:t=5e3,maxDepth:r=12,maxScan:n=5e4}=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},a=[];async function s(t,i){if(a.length>=n||i>r)return;let{data:l,error:o}=await e.storage.from(eC).list(t,{limit:1e3,sortBy:{column:"updated_at",order:"desc"}});if(o)throw o;for(let e of l||[]){if(a.length>=n)break;let r=t?"".concat(t,"/").concat(e.name):e.name;eM.test(e.name)?a.push({path:r,ts:function(e){var t;let r=(null==e?void 0:e.updated_at)||(null==e?void 0:e.created_at)||(null==e||null==(t=e.metadata)?void 0:t.lastModified);if(!r)return 0;let n=Date.parse(String(r));return Number.isFinite(n)?n:0}(e)}):e.name.includes(".")||await s(r,i+1)}}return await s("",0),a.sort((e,t)=>
1t.ts-e.ts),a.slice(0,t).map(e=>e.path)}function eI(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:T.N,{data:r}=t.storage.from(eC).getPublicUrl(e);return(null==r?void 0:r.publicUrl)||""}let eL="/storage/v1/object/public/",eO=new Set(["apparglobal.com","www.apparglobal.com"]);function eR(e){if(!e||"string"!=typeof e)return!1;try{let t=new URL(e);return eO.has(t.hostname)&&t.pathname.includes("/wp-content/uploads/")}catch(e){return!1}}function eD(){let e="https://ooysllobixfyzkgksboh.supabase.co";if(!e)return"";try{return new URL(String(e).trim()).origin}catch(e){return""}}function eB(e){if(!e||"string"!=typeof e)return e||"";if(eR(e))return"";let t=eD();if(!t)return e;try{let r=new URL(e);if(r.origin!==t)return e;let n=r.pathname.indexOf(eL);if(-1===n)return e;let a=r.pathname.slice(n+eL.length).replace(/^\/+/,"");if(!a)return e;let s=a.split("/");return("cms_uploads"===s[0]||"crm-uploads"===s[0])&&(s[0]=eC),a=s.join("/"),"".concat(t).concat(eL).concat(a).concat(r.search).concat(r.hash)}catch(t){return e}}function eF(e){if(!e||"string"!=typeof e)return null;let t="";try{t=new URL(e,"http://localhost").pathname}catch(e){return null}let r=t.indexOf(eL);if(-1!==r){let e=t.slice(r+eL.length).split("/").filter(Boolean);return(("cms_uploads"===e[0]||"crm-uploads"===e[0])&&(e[0]=eC),e[0]===eC&&e.length>=2)?e.slice(1).join("/"):null}let n=t.split("/").filter(Boolean),a=n.findIndex(e=>e===eC||"cms_uploads"===e||"crm-uploads"===e);return -1!==a&&a<n.length-1?n.slice(a+1).join("/"):null}let eU=["BlogPosting","Article","NewsArticle","TechArticle"];function ez(e){let{siteUrl:t,siteName:r,slug:n,post:a}=e;if(!a||!n)return null;let s=String(t||"").replace(/\/$/,""),i=String(a.canonical_url||"").trim()||(s?"".concat(s,"/").concat(String(n).replace(/^\/+|\/+$/g,""),"/"):""),l=String(a.seo_title||"").trim()||String(a.title||"").trim()||String(a.slug||"").trim();if(!l)return null;let o=String(a.excerpt||"").slice(0,500),d=(String(a.seo_description||"").trim().slice(0,500)||o).trim(),c=String(a.cover_image_url||"").trim(),u=String(a.og_image_url||"").trim(),m=u?eB(u):c?eB(c):"",h=m?[m]:[],p={"@context":"https://schema.org","@type":function(e){let t=String(null!=e?e:"").trim();return eU.includes(t)?t:"BlogPosting"}(a.seo_schema_type),headline:l,...d?{description:d}:{},...h.length?{image:h}:{},...i?{mainEntityOfPage:{"@type":"WebPage","@id":i}}:{},publisher:{"@type":"Organization",name:r,...s?{url:s}:{}}},g=String(a.author_display_name||"").trim();if(g&&(p.author={"@type":"Person",name:g}),a.published_at)try{p.datePublished=new Date(a.published_at).toISOString()}catch(e){}if(a.updated_at)try{p.dateModified=new Date(a.updated_at).toISOString()}catch(e){}let x=String(a.category||"").trim();x&&(p.articleSection=x);let f=String(a.meta_keywords||"").trim();f&&(p.keywords=f.split(/[,;]+/).map(e=>e.trim()).filter(Boolean).join(", "));let v=String(a.content||"").replace(/<[^>]+>/g," ").trim().split(/\s+/).filter(Boolean).length;return v>0&&(p.wordCount=v),p}var eK=r(22454);async function eG(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:T.N,r=[...new Set((e||[]).filter(Boolean))];if(!r.length)return[];let{data:n,error:a}=await t.from("cms_media").select("object_path,title,alt_text,caption,description").eq("bucket",eC).in("object_path",r);if(a)throw a;return n||[]}async function eW(e){var t,r,n,a;let s=arguments.length>1&&void 0!==arguments[1]?arguments[1]:T.N,i={bucket:eC,object_path:e.objectPath,title:null!=(t=e.title)?t:"",alt_text:null!=(r=e.altText)?r:"",caption:null!=(n=e.caption)?n:"",description:null!=(a=e.description)?a:""},{error:l}=await s.from("cms_media").upsert(i,{onConflict:"bucket,object_path"});if(l)throw l}async function eH(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:T.N;e&&await t.from("cms_media").delete().eq("bucket",eC).eq("object_path",e)}function eV(e,t){let r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:T.N,n=eI(e,r),a=eI(t,r);if(!n||!a||n===a)return[];let s=[[n,a]],i=eB(n),l=eB(a);i!==n&&s.push([i,l]),s.sort((e,t)=>t[0].length-e[0].length);let o=new Set;return s.filter(e=>{let[t]=e;return!(!t||o.has(t))&&(o.add(t),!0)})}function eQ(e,t){if(null==e||"string"!=typeof e||!e.length)return{next:e,changed:!1};let r=e,n=!1;for(let[e,a]of t)e&&a&&e!==a&&r.includes(e)&&(r=r.split(e).join(a),n=!0);return{next:r,changed:n}}async function eY(e,t){var r,n,a,s,i,l,o,d;let c=arguments.length>2&&void 0!==arguments[2]?arguments[2]:T.N,u=eV(e,t,c);if(!u.length)return 0;let m=0,{data:h,error:p}=await c.from("blog_posts").select("id, content, excerpt, cover_image_url, og_image_url, twitter_image_url");
1if(p)throw p;for(let e of h||[]){let t={},l=eQ(null!=(r=e.content)?r:"",u);l.changed&&(t.content=l.next);let o=eQ(null!=(n=e.excerpt)?n:"",u);o.changed&&(t.excerpt=o.next);let d=eQ(null!=(a=e.cover_image_url)?a:"",u);d.changed&&(t.cover_image_url=d.next);let h=eQ(null!=(s=e.og_image_url)?s:"",u);h.changed&&(t.og_image_url=h.next);let p=eQ(null!=(i=e.twitter_image_url)?i:"",u);if(p.changed&&(t.twitter_image_url=p.next),Object.keys(t).length>0){let{error:r}=await c.from("blog_posts").update(t).eq("id",e.id);if(r)throw r;m+=1}}let{data:g,error:x}=await c.from("page_seo").select("route_path, og_image_url");if(x)throw x;for(let e of g||[]){let t=eQ(null!=(l=e.og_image_url)?l:"",u);if(t.changed){let r=null!=(o=e.route_path)?o:"",{error:n}=await c.from("page_seo").update({og_image_url:t.next}).eq("route_path",r);if(n)throw n;m+=1}}let{data:f,error:v}=await c.from("site_settings").select("*").eq("id",1).maybeSingle();if(v)throw v;if(f&&"object"==typeof f){let e={};for(let t of["default_og_image","default_twitter_image"]){if(!Object.prototype.hasOwnProperty.call(f,t))continue;let r=eQ(String(null!=(d=f[t])?d:""),u);r.changed&&(e[t]=r.next)}if(Object.keys(e).length>0){let{error:t}=await c.from("site_settings").update(e).eq("id",1);if(t)throw t;m+=1}}return m}async function eJ(e,t){let r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:T.N;if(!e)throw Error("Invalid path");let n=function(e){let t=String(e||"").lastIndexOf(".");return t>0?e.slice(t):""}(e.split("/").pop()||"")||".webp",a=e.includes("/")?e.slice(0,e.lastIndexOf("/")):"",s=String(null!=t?t:"").trim();if(n&&s.toLowerCase().endsWith(n.toLowerCase())&&(s=s.slice(0,s.length-n.length).trim()),!s)throw Error("Enter a file name (without changing the extension).");let i="".concat(String(s||"").trim().replace(/\s+/g,"-").replace(/[^a-zA-Z0-9_-]/g,"-").replace(/-+/g,"-").replace(/^-|-$/g,"")||"file").concat(n),l=a?"".concat(a,"/").concat(i):i;if(l===e)return{newObjectPath:e,unchanged:!0};let{error:o}=await r.storage.from(eC).move(e,l);if(o)throw o;let{error:d}=await r.from("cms_media").update({object_path:l}).eq("bucket",eC).eq("object_path",e);if(d)throw d;let c=0;try{c=await eY(e,l,r)}catch(t){let e=(null==t?void 0:t.message)?String(t.message):"Database update failed";throw Error("Storage file was renamed to “".concat(l,"”, but replacing old URLs in the database failed: ").concat(e,". Update posts or revert the file in Storage."))}return{newObjectPath:l,referencesUpdated:c}}var e$=r(82931);function eX(e){let t=String(e||"").trim();return t&&"/"!==t&&t.replace(/\/+$/,"")||"/"}function eZ(e){let t=String(e||"").trim();if(!t||t.startsWith("//")||/^https?:\/\//i.test(t))return t;let r=t,n="",a=t.indexOf("?"),s=t.indexOf("#");return(a>=0?(r=t.slice(0,a),n=t.slice(a)):s>=0&&(r=t.slice(0,s),n=t.slice(s)),"/"===(r=r.replace(/\/+$/,"")||"/"))?n?"/".concat(n):"/":"".concat(r,"/").concat(n)}function e0(e){let t,r=String(e||"").trim();if(!r)return r;try{t=new URL(r)}catch(e){return r}if("http:"!==t.protocol&&"https:"!==t.protocol)return r;let n=t.pathname||"/";if("/"===n||""===n)return"".concat(t.origin,"/").concat(t.search).concat(t.hash);if(n.endsWith("/"))return t.href;let a=n.split("/").filter(Boolean).pop()||"";return/\.[a-z0-9]{2,12}$/i.test(a)||(t.pathname="".concat(n,"/")),t.href}function e1(e){let t=String(e||"").trim();return!t||t.startsWith("//")?t:/^https?:\/\//i.test(t)?e0(t):eZ(t)}function e2(e){let t=String(e||"").trim();return t&&"/"!==t?!(t=t.replace(/\/+$/,"")||"/").startsWith("/")||t.startsWith("//")?t:"/m"===t?"/":t.startsWith("/m/")?(t="/".concat(t.slice(3),"/").replace(/\/{2,}/g,"/")).replace(/\/+$/,"")||"/":"/mobile"===t?"/":t.startsWith("/mobile/")?(t="/".concat(t.slice(8),"/").replace(/\/{2,}/g,"/")).replace(/\/+$/,"")||"/":t:"/"}let e4=new Set(["","catalog","blog","about","support","resources","programs","program","faq","admin","product","privacy-policy","terms-of-service","refund-and-return-policy"]);function e5(e){return String(e).replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function e3(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:eS.W6,r=String(e||"").trim();if(!r)return[];let n=[],a=new Set,s=e=>{let t=String(e||"").trim();if(!t)return;try{/^https?:\/\//i.test(t)&&(t=new URL(t).pathname||"/")}catch(e){return}let r=t.indexOf("?"),s=t.indexOf("#");if(r>
1=0&&(t=t.slice(0,r)),s>=0&&(t=t.slice(0,s)),!(t=t.trim()||"/").startsWith("/")||t.startsWith("//"))return;let i=e2(t.replace(/\/+$/,"")||"/"),l=eX(i);a.has(l)||(a.add(l),n.push(i))};if(/<loc[\s>]/i.test(r))for(let e of function(e,t){let r,n=[],a=new Set,s=t.replace(/\/$/,""),i=/<loc>\s*([^<]+?)\s*<\/loc>/gi;for(;r=i.exec(e);){let e=function(e){let t=String(e||"").trim();return t?t=t.replace(/^(https?:\/\/[^/]+)([a-z][\w\-/%?#&=.]*)/i,(e,t,r)=>e.length>t.length+1&&"/"===e[t.length]?e:"".concat(t,"/").concat(r)):""}(r[1]);if(e)try{let t=new URL(e,s);if(!t.pathname||"/"===t.pathname){a.has("/")||(a.add("/"),n.push("/"));continue}let r=e2(t.pathname.replace(/\/$/,"")||"/");a.has(r)||(a.add(r),n.push(r))}catch(e){}}return n}(r,String(t||eS.W6).replace(/\/$/,"")))s(e);for(let e of r.split(/\r?\n/)){let t=e.trim();!(!t||t.startsWith("#"))&&(/^https?:\/\//i.test(t)?s(t):t.startsWith("/")&&s(t))}let i=[];for(let e of n){if("/"===e)continue;let t=function(e){let t=String(e||"").split("/").filter(Boolean);if(!t.length)return[];let r=[],n=t[t.length-1],a=t[t.length-2];if(n&&!e4.has(n)){let e=e6(n);e.length>=3&&r.push(e)}if(a&&n&&!e4.has(a)&&!e4.has(n)){let e="".concat(e6(a)," ").concat(e6(n)).trim();e.length>=5&&r.push(e)}return[...new Set(r.map(e=>e.replace(/\s+/g," ")))]}(e);if(!t.length){let r=e.split("/").filter(Boolean),n=e6(r[r.length-1]);n.length>=2&&(t=[n])}t.length&&i.push({path:e,phrases:t})}return function(e){let t=new Map;for(let r of e){let e=String(r.path||"").trim();if(!e.startsWith("/")||e.startsWith("//"))continue;let n=Array.isArray(r.phrases)?r.phrases:[];t.has(e)||t.set(e,{path:e,phrases:[]}),t.get(e).phrases.push(...n)}let r=[];for(let{path:e,phrases:n}of t.values()){let t=new Set,a=[];for(let e of n){let r=String(e||"").trim().toLowerCase().replace(/\s+/g," ");r.length<3||t.has(r)||(t.add(r),a.push(e.trim()))}a.sort((e,t)=>t.length-e.length),a.length&&r.push({path:e,phrases:a})}return r}(i)}function e6(e){return String(e||"").replace(/-/g," ").replace(/\s+/g," ").trim()}function e8(e){return String(e||"").replace(/\u00A0/g," ").replace(/\u202F/g," ").replace(/\u2007/g," ").replace(/\u2009/g," ")}
1function e9(e,t){let r=e8(e),n=e8(t.trim());return!n||r.length<n.length?null:function(e,t){let r=t.trim();if(!r||e.length<r.length)return null;try{let t=RegExp("\\b".concat(e5(r),"\\b"),"i").exec(e);if(!t)return null;return{start:t.index,end:t.index+t[0].length}}catch(e){return null}}(r,n)||function(e,t){let r=e8(t.trim()),n=e8(e);if(!r||n.length<r.length)return null;let a=r.split(/\s+/).filter(Boolean);if(!a.length)return null;let s=a.map(e5).join("\\s+");try{let e=RegExp("\\b".concat(s,"\\b"),"i").exec(n);if(!e)return null;return{start:e.index,end:e.index+e[0].length}}catch(e){return null}}(r,n)||function(e,t){let r,n,a=e8(t.trim()),s=e8(e);if(!a||s.length<a.length)return null;let i=a.split(/\s+/).filter(Boolean);if(!i.length)return null;let l=i.map(e5).join("\\s+");try{r=RegExp(l,"gi")}catch(e){return null}for(;null!==(n=r.exec(s));){let e=n.index,t=e+n[0].length,r=0===e?"":s[e-1],a=t>=s.length?"":s[t];if(!RegExp("[\\p{L}\\p{N}]","u").test(r)&&!RegExp("[\\p{L}\\p{N}]","u").test(a))return{start:e,end:t}}return null}(r,n)}let e7=new Set(["A","SCRIPT","STYLE","CODE","PRE","NOSCRIPT"]);function te(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},{includeWhitespace:r=!1}=t,n=[];return!function e(t){if(t.nodeType===Node.TEXT_NODE){let e=t.nodeValue;if(null==e||""===e||!r&&!e.trim())return;n.push(t);return}if(t.nodeType===Node.ELEMENT_NODE&&!e7.has(t.tagName))for(let r of t.childNodes)e(r)}(e),n}function tt(e){return e8(String(e||"")).trim().toLowerCase().replace(/\s+/g," ")}function tr(e,t,r){let n=tt(t);if(!n)return null;for(let a of e.querySelectorAll("a"))if(tt(a.textContent||"")===n)return a.setAttribute("href",e1(r)),{matchedText:String(a.textContent||"").replace(/\u00A0/g," ").trim()||t};return null}function tn(e,t){let r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:12,n=!1;for(let a=0;a<r&&!e9(te(e,{includeWhitespace:!0}).map(e=>e.nodeValue||"").join(""),t);a+=1){let r=!1;for(let a of[...e.querySelectorAll("a")]){let e=(function(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},{includeWhitespace:r=!1}=t,n=[];for(let t of e.childNodes)!function e(t){if(t.nodeType===Node.TEXT_NODE){let e=t.nodeValue;if(null==e||""===e||!r&&!e.trim())return;n.push(t);return}if(t.nodeType===Node.ELEMENT_NODE&&!e7.has(t.tagName))for(let r of t.childNodes)e(r)}(t);return n})(a,{includeWhitespace:!0}).map(e=>e.nodeValue||"").join(""),s=e9(e,t);if(!s||0===s.start&&s.end===e.length)continue;let i=a.parentNode;if(i){for(;a.firstChild;)i.insertBefore(a.firstChild,a);i.removeChild(a),r=!0,n=!0;break}}if(!r)break}return n}function ta(e,t){if(!e.length)return null;let r=t;for(let t of e){let e=(t.nodeValue||"").length;if(r<=e)return{node:t,offset:r};r-=e}let n=e[e.length-1];return{node:n,offset:(n.nodeValue||"").length}}function ts(e,t,r,n,a){let s=t.reduce((e,t)=>e+(t.nodeValue||"").length,0),i=Math.max(0,Math.min(r,s)),l=Math.max(i,Math.min(n,s));if(i>=l)return!1;let o=ta(t,i),d=ta(t,l);if(!o||!d)return!1;let c=e.createRange();c.setStart(o.node,o.offset),c.setEnd(d.node,d.offset);let u=e1(a),m=e.createElement("a");m.setAttribute("href",u),/^https?:\/\//i.test(u)&&(m.setAttribute("rel","noopener noreferrer"),m.setAttribute("target","_blank"));try{c.surroundContents(m)}catch(t){let e=c.extractContents();m.appendChild(e),c.insertNode(m)}return!0}function ti(e){return/^https?:\/\//i.test(String(e||"").trim())}function tl(e){try{let t=new URL(String(e).trim());if("http:"!==t.protocol&&"https:"!==t.protocol)return"";t.hash="";let r=t.pathname;return r.length>1&&r.endsWith("/")&&(r=r.slice(0,-1)),"".concat(t.protocol,"//").concat(t.host.toLowerCase()).concat(r).concat(t.search)}catch(e){return""}}var to=r(71330);async function td(e){let{excludeSlug:t,category:r,limit:n=3}=e;if(!t)return[];let a=new Date().toISOString(),{data:s,error:i}=await T.N.from("blog_posts").select("slug, title, category, cover_image_url, published_at").is("deleted_at",null).neq("slug",t).not("published_at","is",null).lte("published_at",a).order("published_at",{ascending:!1}).limit(24);if(i)throw i;let l=s||[],o=String(r||"").trim();return[...o?l.filter(e=>String(e.category||"").trim()===o):[],...l.filter(e=>!o||String(e.category||"").trim()!==o)].slice(0,n)}async function tc(e){if(!e)return null;let{data:t,error:r}=await T.N.from("blog_posts").select("*").eq("id",e).maybeSingle();if(r)throw r;return t||null}var tu=r(19049),tm=r(98151),th=r(66902);let tp={seoTitleMax:60,metaDescriptionMax:155,focusKeywordMax:80,metaKeywordsMax:280},tg=new Map;function tx(e){var t,r,n,a,s,i,l,o,d,c,u;let m=Number(null!=(d=null!=(o=null!=(l=null!=(i=null!=(s=null==e?void 0:e.status)?s:null==e?void 0:e.statusCode)?i:null==e||null==(t=e.response)?void 0:t.status)?l:null==e||null==(r=e.error)?void 0:r.status)?o:null==e||null==(n=e.cause)?void 0:n.status)?d:NaN);if(429===m||503===m||502===m||408===m||401===m||403===m)return!0;let h="".concat(null!=(c=null==e?void 0:e.message)?c:""," ").concat(null!=(u=null==e||null==(a=e.error)?void 0:a.message)?u:""," ").concat(String(e)).toLowerCase();return!!(/\b429\b/.test(h)||h.includes("rate limit")||h.includes("too many requests")||h.includes("resource exh
1austed")||h.includes("quota")||h.includes("overloaded")||h.includes("unavailable")||h.includes("try again")||h.includes("invalid api key")||h.includes("incorrect api key")||h.includes("api key not valid"))}function tf(e,t){let r=(Array.isArray(t)?t:[]).map(e=>String(null!=e?e:"").trim()).filter(Boolean);if(r.length)return[...new Set(r)];let n=String(null!=e?e:"").trim();return n?[n]:[]}function tv(e){let t=new AbortController,r=setTimeout(()=>t.abort(),e);return{signal:t.signal,cancel:()=>clearTimeout(r)}}function ty(e,t){let r=String(e||"").replace(/\r?\n/g," ").replace(/\s+/g," ").trim();if(r.length<=t)return r;let n=(r=r.slice(0,t).trim()).lastIndexOf(" ");return n>=Math.floor(.55*t)?r.slice(0,n).trim():r}async function tb(e){let{apiKey:t,model:r,prompt:n,signal:a}=e,s=new th.ij(t).getGenerativeModel({model:r,generationConfig:{temperature:.25,maxOutputTokens:1024}});return String((await s.generateContent(n,{signal:a})).response.text()||"").trim()}async function tj(e){var t,r,n,a;let{baseUrl:s,apiKey:i,model:l,prompt:o,extraHeaders:d={},signal:c}=e,u=await fetch("".concat(s,"/chat/completions"),{method:"POST",signal:c,headers:{"Content-Type":"application/json",Authorization:"Bearer ".concat(i),...d},body:JSON.stringify({model:l,temperature:.25,max_tokens:1200,messages:[{role:"user",content:o}]})});if(!u.ok){let e=Error(await u.text()||"".concat(u.status," ").concat(u.statusText));throw e.status=u.status,e}return String(null!=(a=null==(n=(await u.json()).choices)||null==(r=n[0])||null==(t=r.message)?void 0:t.content)?a:"").trim()}async function tw(e,t,r,n,a){switch(e){case"gemini":return tb({apiKey:t,model:r,prompt:n,signal:a});case"openai":return tj({baseUrl:"https://api.openai.com/v1",apiKey:t,model:r,prompt:n,signal:a});case"groq":return tj({baseUrl:"https://api.groq.com/openai/v1",apiKey:t,model:r,prompt:n,signal:a});case"grok":return tj({baseUrl:"https://api.x.ai/v1",apiKey:t,model:r,prompt:n,signal:a});case"openrouter":return tj({baseUrl:"https://openrouter.ai/api/v1",apiKey:t,model:r,prompt:n,signal:a,extraHeaders:{"HTTP-Referer":eS.W6,"X-Title":"Appar Admin — SEO pack"}});default:throw Error("Unknown provider: ".concat(e))}}function t_(e){var t,r,n,a,s,i,l,o;let d,c,u=((c=String(e||"").trim()).startsWith("```")&&(c=c.replace(/^```(?:json)?\s*/i,"").replace(/\s*```\s*$/i,"")),c.trim());try{d=JSON.parse(u)}catch(e){throw Error("Model did not return valid JSON. Try again or switch model.")}if(!d||"object"!=typeof d)throw Error("Invalid SEO JSON shape from model.");let m=ty(null!=(r=null!=(t=d.seo_title)?t:d.seoTitle)?r:"",tp.seoTitleMax),h=ty(null!=(a=null!=(n=d.meta_description)?n:d.metaDescription)?a:"",tp.metaDescriptionMax),p=ty(null!=(i=null!=(s=d.focus_keyword)?s:d.focusKeyword)?i:"",tp.focusKeywordMax),g=function(e,t){let r=String(e||"").split(",").map(e=>e.trim()).filter(Boolean),n=[],a=0;for(let e of r){let r=0===a?e:"".concat(n.join(", "),", ").concat(e);if(r.length>t)break;n.push(e),a=r.length}return n.join(", ")}(null!=(o=null!=(l=d.meta_keywords)?l:d.metaKeywords)?o:"",tp.metaKeywordsMax);if(!m&&!h&&!p&&!g)throw Error("Model returned empty SEO fields.");return{seo_title:m,meta_description:h,focus_keyword:p,meta_keywords:g}}async function tN(e){var t;let r,{provider:n,apiKey:a,apiKeys:s,model:i,routePath:l,pageName:o,timeoutMs:d=6e4}=e,c=tf(a,s);if(!c.length)throw Error("Missing API key — set it in Admin → API Settings.");if(!(null==i?void 0:i.trim()))throw Error("Missing model — choose one in API Settings.");if(!(null==l?void 0:l.trim()))throw Error("Route path is required.");let u=function(e){let{routePath:t,pageName:r,siteUrl:n}=e,a=r&&r!==t?"Page name: ".concat(r,"\nRoute: ").concat(t):"Route: ".concat(t);return"You are an SEO editor for ".concat(n||"a business website",'. Return ONLY a single JSON object (no markdown fences, no commentary) with exactly these keys:\n"seo_title", "meta_description", "focus_keyword", "meta_keywords"\n\nFollow Google-oriented best practices:\n\n1) seo_title\n   - Maximum ').concat(tp.seoTitleMax," characters. Put the main topic first; natural, compelling language.\n   - Do NOT append the site name — it will be added separately.\n\n2) meta_description\n   - Maximum ").concat(tp.metaDescriptionMax," characters. Lead with value in the first ~120 chars for mobile.\n   - Compelling, accurate; include key terms naturally.\n\n3) focus_keyword\n   - ONE primary phrase (2–6 words) this page should target; maximum ").concat(tp.focusKeywordMax," characters; no commas.\n\n4) meta_keywords\n   - Comma-separated list of 5–10 relevant phrases; total maximum ").concat(tp.metaKeywordsMax,' characters.\n\nRules:\n- Base fields on the page route/name context below. Infer what the page is about from the URL slug and name.\n- Output must be ONLY a JSON object: f
1irst non-whitespace char must be "{", last must be "}".\n- Use double quotes for JSON keys and string values.\n\nPage context:\n').concat(a)}({routePath:l.trim(),pageName:(o||"").trim(),siteUrl:eS.W6}),m=c.length,h=null!=(t=tg.get(n))?t:0;h=(h%m+m)%m;for(let e=0;e<m;e+=1){let t=c[(h+e)%m],{signal:a,cancel:s}=tv(d);try{let r=await tw(n,t,i,u,a);return tg.set(n,(h+e+1)%m),t_(r)}catch(t){if(r=(null==t?void 0:t.name)==="AbortError"?Error("Request timed out — try again."):t,!(tx(t)&&e<m-1))throw r}finally{s()}}throw r||Error("All API keys failed.")}async function tk(e){var t;let r,{provider:n,apiKey:a,apiKeys:s,model:i,htmlContent:l,postTitle:o="",timeoutMs:d=9e4}=e,c=tf(a,s);if(!c.length)throw Error("Missing API key — set it in Admin → API Settings.");if(!(null==i?void 0:i.trim()))throw Error("Missing model — choose one in API Settings.");let u=String(l||"").replace(/<[^>]+>/g," ").replace(/\s+/g," ").trim();if(u.length<24)throw Error("Add more body content first so the model can derive SEO fields.");let m=u.length>12e4?"".concat(u.slice(0,12e4),"\n\n[Article truncated for length.]"):u,h=function(e){let{postTitle:t,articlePlain:r}=e;return'You are an SEO editor. Return ONLY a single JSON object (no markdown fences, no commentary) with exactly these keys:\n"seo_title", "meta_description", "focus_keyword", "meta_keywords"\n\nFollow Google-oriented best practices (SERP display uses pixel width; character limits below avoid most truncation):\n\n1) seo_title\n   - Maximum '.concat(tp.seoTitleMax," characters (including spaces). Aim ~50–60. Put the main topic first; natural language; no pipe-stuffed spam.\n   - Should work as the HTML <title> / snippet title; do not repeat the site brand unless it fits and helps clarity.\n\n2) meta_description\n   - Maximum ").concat(tp.metaDescriptionMax," characters. Put the most important message in the first ~120 characters for mobile snippets.\n   - Compelling, accurate summary; include key terms naturally; no quotes wrapping the entire string.\n\n3) focus_keyword\n   - ONE primary phrase (2–6 words) the article should target; maximum ").concat(tp.focusKeywordMax," characters; no commas.\n\n4) meta_keywords\n   - Comma-separated list of 5–10 short relevant phrases; total string maximum ").concat(tp.metaKeywordsMax,' characters (legacy meta tag).\n\nRules:\n- Base ALL fields ONLY on the article (and post title for context). Do not invent offers, numbers, or claims not in the text.\n- Output must be ONLY a JSON object: your first non-whitespace character must be "{" and your last must be "}".\n- Use double quotes for JSON keys and string values. Escape any double quotes inside strings.\n\nPost title:\n').concat(t||"(no title)","\n\nArticle (plain text):\n").concat(r)}({postTitle:String(o||"").trim(),articlePlain:m}),p=c.length,g=null!=(t=tg.get(n))?t:0;g=(g%p+p)%p;for(let e=0;e<p;e+=1){let t=c[(g+e)%p],{signal:a,cancel:s}=tv(d);try{let r=await tw(n,t,i,h,a);return tg.set(n,(g+e+1)%p),t_(r)}catch(t){if(r=(null==t?void 0:t.name)==="AbortError"?Error("Request timed out — try again."):t,!(tx(t)&&e<p-1))throw r}finally{s()}}throw r||Error("All API keys failed.")}let tS=tp.seoTitleMax,tC=tp.metaDescriptionMax;function tA(){return{h1:0,h2:0,h3:0,h4:0,h5:0,h6:0}}function tE(e){let t=String((null==e?void 0:e.seo_title)||"").trim();return t||String((null==e?void 0:e.title)||"").trim()}function tT(e){let t=String((null==e?void 0:e.seo_description)||"").trim();return t||String((null==e?void 0:e.excerpt)||"").trim()}function tq(e){let t=new Map;for(let r of e){let e=tM(tE(r));e&&t.set(e,(t.get(e)||0)+1)}return t}function tM(e){return String(e||"").trim().toLowerCase().replace(/\s+/g," ")}function tP(e,t,r){let n=[],a=[],s=tE(e),i=tT(e);s?(s.length<15&&n.push("Title very short (".concat(s.length," chars; aim for ≥").concat(15,")")),s.length>tS&&a.push("SEO title may truncate in SERPs (".concat(s.length," chars; ≤").concat(tS," is safer)"))):n.push("Missing title and SEO title"),String((null==e?void 0:e.seo_title)||"").trim()||s!==String((null==e?void 0:e.title)||"").trim()||a.push("Custom SEO title not set (using post title)"),i?i.length<70?n.push("Meta description short (".concat(i.length," chars; aim for ~").concat(70,"–").concat(tC,")")):i.length>tC&&a.push("Meta description may truncate (".concat(i.length," chars; ≤").concat(tC," typical)")):n.push("Missing meta description (and excerpt)");let l=tM(s);l&&(r.get(l)||0)>1&&n.push("Duplicate SEO title vs another post"),!function(e){let t=String((null==e?void 0:e.cover_image_url)||"").trim(),r
1=String((null==e?void 0:e.og_image_url)||"").trim(),n=String((null==e?void 0:e.twitter_image_url)||"").trim();return!!(t||r||n)}(e)&&a.push("No cover image and no custom OG/Twitter image — the live article still shows a placeholder hero and OG image until you add a cover (or set OG/Twitter image)");let o=function(e){let t,r=String(e||"").trim();if(!r)return{headingCounts:tA(),h1Count:0,imagesTotal:0,imagesMissingAlt:0,internalLinkCount:0,externalLinkCount:0};try{t=new DOMParser().parseFromString(r,"text/html")}catch(e){return{headingCounts:tA(),h1Count:0,imagesTotal:0,imagesMissingAlt:0,internalLinkCount:0,externalLinkCount:0}}let n=tA();for(let e=1;e<=6;e+=1){let r="h".concat(e);n[r]=t.querySelectorAll(r).length}let a=n.h1,s=t.querySelectorAll("img"),i=0;s.forEach(e=>{let t=e.getAttribute("alt");(null===t||""===String(t).trim())&&(i+=1)});let l=(()=>{try{return new URL(eS.W6).origin}catch(e){return""}})(),o=0,d=0;return t.querySelectorAll("a[href]").forEach(e=>{let t=e.getAttribute("href");if(!(!t||t.startsWith("#")||t.trim().toLowerCase().startsWith("mailto:"))){if(t.startsWith("/")){o+=1;return}try{let e=new URL(t,eS.W6);l&&e.origin===l?o+=1:/^https?:/i.test(t)&&(d+=1)}catch(e){}}}),{headingCounts:n,h1Count:a,imagesTotal:s.length,imagesMissingAlt:i,internalLinkCount:o,externalLinkCount:d}}(t),d={headingCounts:o.headingCounts,imagesTotal:o.imagesTotal,imagesMissingAlt:o.imagesMissingAlt,internalLinkCount:o.internalLinkCount,externalLinkCount:o.externalLinkCount};if(null!=t&&String(t).trim()){var c,u;o.h1Count>0&&n.push(1===o.h1Count?"Body contains an H1 — the live article already uses the post title as the page H1. Use H2 (or below) for headings inside the body.":"Body has ".concat(o.h1Count," H1 tags — the post title is the page H1; change these to H2+ so only one H1 exists on the page.")),o.imagesTotal>0&&o.imagesMissingAlt>0&&n.push("".concat(o.imagesMissingAlt," image(s) missing alt text")),0===o.internalLinkCount&&a.push("No internal links in body"),0===o.externalLinkCount&&a.push("No external links in body (optional: link to reputable sources when it helps readers)"),(null!=(u=null==(c=o.headingCounts)?void 0:c.h2)?u:0)>15&&a.push("Many H2 headings (".concat(o.headingCounts.h2,") — consider fewer top-level sections or use H3 for sub-points"))}let m="ok";return n.length>0?m="bad":a.length>0&&(m="warn"),{level:m,issues:n,hints:a,bodyStats:d}}async function tI(){let{data:e,error:t}=await T.N.from("blog_posts").select("id, slug, title, category, featured, published_at, updated_at, created_at, created_by, deleted_at, excerpt, seo_title, seo_description, meta_keywords, focus_keyword, cover_image_url, og_image_url, twitter_image_url").order("updated_at",{ascending:!1});if(t)throw t;let{data:r,error:n}=await T.N.rpc("admin_list_users_with_roles");if(n)throw n;let a=(r||[]).sort((e,t)=>(e.email||"").localeCompare(t.email||"")),s=Object.fromEntries(a.map(e=>{var t;return[e.id,{email:null!=(t=e.email)?t:"",displayName:"string"==typeof e.display_name?e.display_name.trim():""}]})),{data:i,error:l}=await T.N.from("blog_post_edit_sessions").select("post_id, user_id, updated_at");if(l)throw l;let o=Date.now(),d={};for(let e of i||[]){let t=new Date(e.updated_at).getTime();Number.isNaN(t)||o-t>1e5||(d[e.post_id]={userId:e.user_id,updatedAt:e.updated_at})}return{posts:e||[],authorById:s,usersForAuthor:a,editSessionsByPostId:d}}async function tL(){var e,t;let[r,n]=await Promise.all([T.N.from("blog_posts").select("id",{count:"exact",head:!0}).is("deleted_at",null),T.N.from("page_seo").select("id",{count:"exact",head:!0})]);if(r.error)throw r.error;if(n.error)throw n.error;return{posts:null!=(e=r.count)?e:0,pages:null!=(t=n.count)?t:0}}var tO=r(80549),tR=r(56023);let tD=(0,v.F)("inline-flex items-center rounded-md border px-2.5 py-0.5 text-xs font-semibold transition-colors focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2",{variants:{variant:{default:"border-transparent bg-primary text-primary-foreground shadow hover:bg-primary/80",secondary:"border-transparent bg-secondary text-secondary-foreground hover:bg-secondary/80",destructive:"border-transparent bg-destructive text-destructive-foreground shadow hover:bg-destructive/80",outline:"text-foreground"}},defaultVariants:{variant:"default"}});function tB(e){let{className:t,variant:r,...a}=e;return(0,n.jsx)("div",{className:(0,b.cn)(tD({variant:r}),t),...a})}var tF=r(90109),tU=r(11064),tz=r(27314);async function tK(){let{data:e,error:t}=await T.N.rpc("admin_list_users_with_roles");if(t)throw console.error("Error fetching users:",t),t;return(e||[]).sort((e,t)=>
1new Date(t.created_at).getTime()-new Date(e.created_at).getTime())}var tG=r(10489);let tW=(0,v.F)("text-sm font-medium leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-70"),tH=a.forwardRef((e,t)=>{let{className:r,...a}=e;return(0,n.jsx)(tG.b,{ref:t,className:(0,b.cn)(tW(),r),...a})});tH.displayName=tG.b.displayName;var tV=r(89511);let tQ=tV.bL,tY=tV.l9,tJ=tV.ZL;tV.bm;let t$=a.forwardRef((e,t)=>{let{className:r,...a}=e;return(0,n.jsx)(tV.hJ,{ref:t,className:(0,b.cn)("fixed inset-0 z-50 bg-black/80  data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0",r),...a})});t$.displayName=tV.hJ.displayName;let tX=a.forwardRef((e,t)=>{let{className:r,children:a,hideCloseButton:s,...i}=e;return(0,n.jsxs)(tJ,{children:[(0,n.jsx)(t$,{}),(0,n.jsxs)(tV.UC,{ref:t,className:(0,b.cn)("fixed left-[50%] top-[50%] z-50 grid w-full max-w-lg translate-x-[-50%] translate-y-[-50%] gap-4 border bg-background p-6 shadow-lg duration-200 data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[state=closed]:slide-out-to-left-1/2 data-[state=closed]:slide-out-to-top-[48%] data-[state=open]:slide-in-from-left-1/2 data-[state=open]:slide-in-from-top-[48%] sm:rounded-lg",r),...i,children:[a,s?null:(0,n.jsxs)(tV.bm,{className:"absolute right-4 top-4 roun
1ded-sm opacity-70 ring-offset-background transition-opacity hover:opacity-100 focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2 disabled:pointer-events-none data-[state=open]:bg-accent data-[state=open]:text-muted-foreground",children:[(0,n.jsx)(y.A,{className:"h-4 w-4"}),(0,n.jsx)("span",{className:"sr-only",children:"Close"})]})]})]})});tX.displayName=tV.UC.displayName;let tZ=e=>{let{className:t,...r}=e;return(0,n.jsx)("div",{className:(0,b.cn)("flex flex-col space-y-1.5 text-center sm:text-left",t),...r})};tZ.displayName="DialogHeader";let t0=e=>{let{className:t,...r}=e;return(0,n.jsx)("div",{className:(0,b.cn)("flex flex-col-reverse sm:flex-row sm:justify-end sm:space-x-2",t),...r})};t0.displayName="DialogFooter";let t1=a.forwardRef((e,t)=>{let{className:r,...a}=e;return(0,n.jsx)(tV.hE,{ref:t,className:(0,b.cn)("text-lg font-semibold leading-none tracking-tight",r),...a})});t1.displayName=tV.hE.displayName;let t2=a.forwardRef((e,t)=>{let{className:r,...a}=e;return(0,n.jsx)(tV.VY,{ref:t,className:(0,b.cn)("text-sm text-muted-foreground",r),...a})});function t4(e){return String(e||"").toLowerCase().trim().replace(/['"]/g,"").replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"")}async function t5(){let{data:e,error:t}=await T.N.from("blog_categories").select("id, name, slug, sort_order, created_at").order("sort_order",{ascending:!0}).order("name",{ascending:!0});if(t)throw t;return e||[]}async function t3(e){let{count:t,error:r}=await T.N.from("blog_posts").select("id",{count:"exact",head:!0}).eq("category",e);if(r)throw r;return null!=t?t:0}function t6(e){var t,r,s;let{row:i,onCancel:l,onSave:o,isSaving:d}=e,[c,u]=(0,a.useState)(null!=(t=null==i?void 0:i.name)?t:""),[m,h]=(0,a.useState)(null!=(r=null==i?void 0:i.slug)?r:""),[p,g]=(0,a.useState)(null!=(s=i.sort_order)?s:0);return(0,n.jsxs)("div",{className:"grid gap-4 pt-2",children:[(0,n.jsxs)("div",{className:"grid gap-2",children:[(0,n.jsx)(tH,{htmlFor:"edit-name",children:"Name"}),(0,n.jsx)(tR.p,{id:"edit-name",value:c,onChange:e=>u(e.target.value)})]}),(0,n.jsxs)("div",{className:"grid gap-2",children:[(0,n.jsx)(tH,{htmlFor:"edit-slug",children:"Slug"}),(0,n.jsx)(tR.p,{id:"edit-slug",value:m,onChange:e=>h(e.target.value)})]}),(0,n.jsxs)("div",{className:"grid gap-2",children:[(0,n.jsx)(tH,{htmlFor:"edit-sort",children:"Sort order"}),(0,n.jsx)(tR.p,{id:"edit-sort",type:"number",value:p,onChange:e=>g(Number(e.target.value)||0)})]}),(0,n.jsxs)("div",{className:"flex justify-end gap-2",children:[(0,n.jsx)(L.Button,{type:"button",variant:"outline",onClick:l,children:"Cancel"}),(0,n.jsx)(L.Button,{type:"button",disabled:d||!c.trim(),onClick:()=>o({name:c.trim(),slug:(m.trim()||t4(c)).trim(),sort_order:p}),children:d?"Saving…":"Save"})]})]})}t2.displayName=tV.VY.displayName;var t8=r(60574);let t9=t8.bL,t7=a.forwardRef((e,t)=>{let{className:r,...a}=e;return(0,n.jsx)(t8.B8,{ref:t,className:(0,b.cn)("inline-flex h-9 items-center justify-center rounded-lg bg-muted p-1 text-muted-foreground",r),...a})});t7.displayName=t8.B8.displayName;let re=a.forwardRef((e,t)=>{let{className:r,...a}=e;return(0,n.jsx)(t8.l9,{ref:t,className:(0,b.cn)("inline-flex items-center justify-center whitespace-nowrap rounded-md px-3 py-1 text-sm font-medium ring-offset-background transition-all focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:pointer-events-none disabled:opacity-50 data-[state=active]:bg-background data-[state=active]:text-foreground data-[state=active]:shadow",r),...a})});re.displayName=t8.l9.displayName;let rt=a.forwardRef((e,t)=>{let{className:r,...a}=e;return(0,n.jsx)(t8.UC,{ref:t,className:(0,b.cn)("mt-2 ring-offset-background focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2",r),...a})});rt.displayName=t8.UC.displayName;var rr=r(38162),rn=r(72251);let ra=a.forwardRef((e,t)=>{let{className:r,...a}=e;return(0,n.jsx)(rr.bL,{ref:t,className:(0,b.cn)("peer h-4 w-4 shrink-0 rounded-sm border border-primary shadow focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring disabled:cursor-not-allowed disabled:opacity-50 data-[state=checked]:bg-primary data-[state=checked]:text-primary-foreground",r),...a,children:(0,n.jsx)(rr.C1,{className:(0,b.cn)("flex items-center justify-center text-current"),children:(0,n.jsx)(rn.A,{className:"h-4 w-4"})})})});ra.displayName=rr.bL.displayName;var rs=r(55644),ri=r(42614);let rl=rs.bL;rs.YJ;let ro=rs.WT,rd=a.forwardRef((e,t)=>
1{let{className:r,children:a,...s}=e;return(0,n.jsxs)(rs.l9,{ref:t,className:(0,b.cn)("flex h-9 w-full items-center justify-between whitespace-nowrap rounded-md border border-input bg-transparent px-3 py-2 text-sm shadow-sm ring-offset-background data-[placeholder]:text-muted-foreground focus:outline-none focus:ring-1 focus:ring-ring disabled:cursor-not-allowed disabled:opacity-50 [&>span]:line-clamp-1",r),...s,children:[a,(0,n.jsx)(rs.In,{asChild:!0,children:(0,n.jsx)(U.A,{className:"h-4 w-4 opacity-50"})})]})});rd.displayName=rs.l9.displayName;let rc=a.forwardRef((e,t)=>{let{className:r,...a}=e;return(0,n.jsx)(rs.PP,{ref:t,className:(0,b.cn)("flex cursor-default items-center justify-center py-1",r),...a,children:(0,n.jsx)(ri.A,{className:"h-4 w-4"})})});rc.displayName=rs.PP.displayName;let ru=a.forwardRef((e,t)=>{let{className:r,...a}=e;return(0,n.jsx)(rs.wn,{ref:t,className:(0,b.cn)("flex cursor-default items-center justify-center py-1",r),...a,children:(0,n.jsx)(U.A,{className:"h-4 w-4"})})});ru.displayName=rs.wn.displayName;let rm=a.forwardRef((e,t)=>{let{className:r,children:a,position:s="popper",...i}=e;return(0,n.jsx)(rs.ZL,{children:(0,n.jsxs)(rs.UC,{ref:t,className:(0,b.cn)("relative z-50 max-h-96 min-w-[8rem] overflow-hidden rounded-md border bg-popover text-popover-foreground shadow-md data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2","popper"===s&&"data-[side=bottom]:translate-y-1 data-[side=left]:-translate-x-1 data-[side=right]:translate-x-1 data-[side=top]:-translate-y-1",r),position:s,...i,children:[(0,n.jsx)(rc,{}),(0,n.jsx)(rs.LM,{className:(0,b.cn)("p-1","popper"===s&&"h-[var(--radix-select-trigger-height)] w-full min-w-[var(--radix-select-trigger-width)]"),children:a}),(0,n.jsx)(ru,{})]})})});rm.displayName=rs.UC.displayName,a.forwardRef((e,t)=>{let{className:r,...a}=e;return(0,n.jsx)(rs.JU,{ref:t,className:(0,b.cn)("px-2 py-1.5 text-sm font-semibold",r),...a})}).displayName=rs.JU.displayName;let rh=a.forwardRef((e,t)=>{let{className:r,children:a,...s}=e;return(0,n.jsxs)(rs.q7,{ref:t,className:(0,b.cn)("relative flex w-full cursor-default select-none items-center rounded-sm py-1.5 pl-2 pr-8 text-sm outline-none focus:bg-accent focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50",r),...s,children:[(0,n.jsx)("span",{className:"absolute right-2 flex h-3.5 w-3.5 items-center justify-center",children:(0,n.jsx)(rs.VF,{children:(0,n.jsx)(rn.A,{className:"h-4 w-4"})})}),(0,n.jsx)(rs.p4,{children:a})]})});rh.displayName=rs.q7.displayName;let rp=a.forwardRef((e,t)=>{let{className:r,...a}=e;return(0,n.jsx)(rs.wv,{ref:t,className:(0,b.cn)("-mx-1 my-1 h-px bg-muted",r),...a})});rp.displayName=rs.wv.displayName;var rg=r(92033),rx=r(61270),rf=r(47520);let rv=rf.Kq,ry=rf.bL,rb=rf.l9,rj=a.forwardRef((e,t)=>{let{className:r,sideOffset:a=4,...s}=e;return(0,n.jsx)(rf.ZL,{children:(0,n.jsx)(rf.UC,{ref:t,sideOffset:a,className:(0,b.cn)("z-50 overflow-hidden rounded-md bg-primary px-3 py-1.5 text-xs text-primary-foreground animate-in fade-in-0 zoom-in-95 data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=closed]:zoom-out-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2",r),...s})})});rj.displayName=rf.UC.displayName;let rw="__none__",r_="__unassigned__";async function rN(){let{data:e,error:t}=await T.N.from("blog_categories").select("name").order("sort_order",{ascending:!0}).order("name",{ascending:!0});if(!t&&(null==e?void 0:e.length))return e.map(e=>String(e.name||"").trim()).filter(Boolean);let{data:r,error:n}=await T.N.from("blog_posts").select("category").is("deleted_at",null);return n?[]:[...new Set((r||[]).map(e=>String(e.category||"").trim()).filter(Boolean))].sort((e,t)=>
1e.localeCompare(t))}function rk(e){if(!e)return null;let t=new Date(e);return Number.isNaN(t.getTime())?null:"".concat(t.getFullYear(),"-").concat(String(t.getMonth()+1).padStart(2,"0"))}function rS(e){return e.published_at||e.updated_at||e.created_at}function rC(e){if(!e||"string"!=typeof e)return"";let t=e.indexOf("@");return t>0?e.slice(0,t):e}function rA(e,t){if(!e.created_by)return"—";let r=t[e.created_by];return r?r.displayName?r.displayName:rC(r.email)||"—":"—"}function rE(e){let t="string"==typeof e.display_name?e.display_name.trim():"";return t||rC(e.email)||e.id}function rT(e,t,r,n){if("trash"===t)return!1;let a=r[e];return!!(null==a?void 0:a.userId)&&(!n||a.userId!==n)}function rq(e){var t;let{post:r,bodyHtml:a,duplicateTitleCounts:s,bodyLoading:i}=e,{level:l,issues:o,hints:d,bodyStats:c}=tP(r,a,s),u=[...o.map(e=>({t:e,kind:"issue"})),...d.map(e=>({t:e,kind:"hint"}))];return(0,n.jsx)(rv,{delayDuration:200,children:(0,n.jsxs)(ry,{children:[(0,n.jsx)(rb,{asChild:!0,children:(0,n.jsxs)("button",{type:"button",className:(0,b.cn)("inline-flex min-h-8 w-full max-w-[5.75rem] items-center justify-center gap-1 rounded-md border px-2 py-1 text-xs font-medium transition-colors","ok"===l?"border-emerald-300/80 bg-emerald-50 text-emerald-900 dark:border-emerald-700 dark:bg-emerald-950/50 dark:text-emerald-100":"warn"===l?"border-amber-300/80 bg-amber-50 text-amber-950 dark:border-amber-700 dark:bg-amber-950/40 dark:text-amber-100":"border-destructive/40 bg-destructive/10 text-destructive dark:bg-destructive/20"),children:[i?(0,n.jsx)(rg.A,{className:"h-3.5 w-3.5 shrink-0 animate-spin opacity-80","aria-hidden":!0}):null,(0,n.jsx)("span",{children:"ok"===l?"Good":"warn"===l?"Review":"Fix"})]})}),(0,n.jsxs)(rj,{side:"left",sideOffset:6,className:"z-50 max-w-[min(22rem,calc(100vw-2rem))] border border-border bg-popover px-3 py-2 text-popover-foreground shadow-md",children:[!i&&c?(0,n.jsx)("p",{className:"text-[11px] font-mono leading-snug text-muted-foreground border-b border-border pb-2 mb-2",children:(t=c.headingCounts,[1,2,3,4,5,6].map(e=>{var r;return"H".concat(e,":").concat(Number(null!=(r=null==t?void 0:t["h".concat(e)])?r:0))}).join(" "))}):null,i&&0===u.length?(0,n.jsx)("p",{className:"text-xs text-muted-foreground",children:"Checking body (headings, alt text, links)…"}):0===u.length?(0,n.jsx)("p",{className:"text-xs",children:"No obvious SEO issues detected."}):(0,n.jsxs)("ul",{className:"max-h-48 list-disc space-y-1 overflow-y-auto pl-4 text-xs leading-snug",children:[u.map((e,t)=>(0,n.jsx)("li",{className:"hint"===e.kind?"text-muted-foreground":"",children:e.t},t)),i?(0,n.jsx)("li",{className:"list-none pl-0 text-muted-foreground",children:"Still checking body…"}):null]})]})]})})}function rM(e){let t=Date.now(),r=e.published_at?new Date(e.published_at).getTime():null;return{isPublished:!!r&&r<=t,isScheduled:!!r&&r>t,publishedAt:r}}var rP=r(91563),rI=r(27599);let rL=a.forwardRef((e,t)=>{let{className:r,...a}=e;return(0,n.jsx)(rI.bL,{className:(0,b.cn)("peer inline-flex h-5 w-9 shrink-0 cursor-pointer items-center rounded-full border-2 border-transparent shadow-sm transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 focus-visible:ring-offset-background disabled:cursor-not-allowed disabled:opacity-50 data-[state=checked]:bg-primary data-[state=unchecked]:bg-input",r),...a,ref:t,children:(0,n.jsx)(rI.zi,{className:(0,b.cn)("pointer-events-none block h-4 w-4 rounded-full bg-background shadow-lg ring-0 transition-transform data-[state=checked]:translate-x-4 data-[state=unchecked]:translate-x-0")})})});rL.displayName=rI.bL.displayName;var rO=r(74640);async function rR(e){var t;let{maxWidth:r=1600,maxHeight:n=1600,quality:a=.82,mimeType:s="image/webp",forceTargetMime:i=!1}=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};if(!e||!(null==(t=e.type)?void 0:t.startsWith("image/"))||"image/svg+xml"===e.type||!i&&e.size<=256e3)return e;let l=await createImageBitmap(e),o=l.width||1,d=l.height||1,c=Math.min(1,r/o,n/d),u=Math.max(1,Math.round(o*c)),m=
1Math.max(1,Math.round(d*c)),h=document.createElement("canvas");h.width=u,h.height=m;let p=h.getContext("2d",{alpha:!1});if(!p)return e;p.imageSmoothingEnabled=!0,p.imageSmoothingQuality="high",p.drawImage(l,0,0,u,m);let g=await new Promise(e=>h.toBlob(e,s,a));if(!g||!i&&g.size>=e.size)return e;let x="image/webp"===s?"webp":"image/jpeg"===s?"jpg":"",f=e.name.replace(/\.[^.]+$/,"")||"image";return new File([g],x?"".concat(f,".").concat(x):e.name,{type:g.type,lastModified:Date.now()})}function rD(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:"",t=e.lastIndexOf(".");return t>=0?e.slice(t+1).toLowerCase():""}function rB(e){let{open:t,onOpenChange:r,title:s="Add media",confirmLabel:i="Insert into post",onConfirm:l,uploadMaxWidth:d=1600,uploadMaxHeight:c=1600,uploadQuality:u=.82,uploadFormat:m="webp"}=e,h=(0,o.jE)(),[p,g]=(0,a.useState)("upload"),[x,v]=(0,a.useState)(null),[y,b]=(0,a.useState)(""),[j,w]=(0,a.useState)(!1),[_,N]=(0,a.useState)(""),k=(0,a.useRef)(null),{data:S=[],isLoading:C}=(0,eK.I)({queryKey:["admin","cms-media",eC],queryFn:()=>eP(T.N),staleTime:2e4,enabled:t}),A=(0,a.useMemo)(()=>S.map(e=>{let t=eI(e,T.N);return{objectPath:e,storageUrl:t}}),[S]),E=(0,a.useMemo)(()=>{let e=_.trim().toLowerCase();return e?A.filter(t=>{let{objectPath:r}=t;return r.toLowerCase().includes(e)}):A},[A,_]);(0,a.useEffect)(()=>{t||(g("upload"),v(null),b(""),N(""))},[t]);let q=(0,a.useCallback)((e,t)=>{v(e),b(t)},[]),M=(0,a.useCallback)(async e=>{var t;if(e&&(null==(t=e.type)?void 0:t.startsWith("image/"))){w(!0);try{let t="keep"===m?e.type:"jpg"===m?"image/jpeg":"image/webp",r=await rR(e,{maxWidth:d,maxHeight:c,quality:u,mimeType:t,forceTargetMime:"keep"!==m}),n=rD(r.name)||"webp",a=eq(e.name,"jpg"===n||"jpeg"===n?"jpg":"png"===n||"gif"===n?n:"webp"),{error:s}=await T.N.storage.from(eC).upload(a,r,{upsert:!0,contentType:r.type||void 0});if(s)throw s;let i=eI(a,T.N);v(a),b(i),g("library"),await h.invalidateQueries({queryKey:["admin","cms-media",eC]}),f({title:"Uploaded",description:"Choose Insert or pick another file."})}catch(e){f({title:"Upload failed",description:(null==e?void 0:e.message)||"Unknown error",variant:"destructive"})}finally{w(!1)}}},[h,d,c,u,m]);return(0,n.jsx)(tQ,{open:t,onOpenChange:r,children:(0,n.jsxs)(tX,{className:"flex max-h-[min(92vh,820px)] w-[min(960px,calc(100vw-1rem))] max-w-none flex-col gap-0 overflow-hidden p-0 sm:rounded-xl",children:[(0,n.jsx)(tZ,{className:"border-b border-border/80 px-5 py-4 pr-12",children:(0,n.jsx)(t1,{className:"text-left text-lg",children:s})}),(0,n.jsxs)(t9,{value:p,onValueChange:g,className:"flex min-h-0 flex-1 flex-col gap-0",children:[(0,n.jsxs)("div",{className:"flex flex-wrap items-center justify-between gap-3 border-b border-border/60 bg-muted/20 px-5 py-3",children:[(0,n.jsxs)(t7,{className:"h-9 bg-background/80",children:[(0,n.jsx)(re,{value:"upload",className:"px-4",children:"Upload files"}),(0,n.jsx)(re,{value:"library",className:"px-4",children:"Media Library"})]}),"library"===p?(0,n.jsx)("input",{type:"search",placeholder:"Search files…",value:_,onChange:e=>N(e.target.value),className:"h-9 w-full max-w-xs rounded-md border border-input bg-background px-3 text-sm shadow-sm focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring"}):null]}),(0,n.jsx)(rt,{value:"upload",className:"m-0 flex-1 overflow-y-auto focus-visible:outline-none",children:(0,n.jsxs)("div",{className:"flex min-h-[280px] flex-col items-center justify-center gap-4 px-6 py-12 text-center",onDragOver:e=>e.preventDefault(),onDrop:function(e){var t,r;e.preventDefault(),M(null==(r=e.dataTransfer)||null==(t=r.files)?void 0:t[0])},children:[(0,n.jsx)("p",{className:"text-sm text-muted-foreground",children:"Drop files to upload"}),(0,n.jsx)("p",{className:"text-xs text-muted-foreground",children:"or"}),(0,n.jsx)("input",{ref:k,type:"file",accept:"image/*",className:"hidden",disabled:j,onChange:function(e){var t;let r=null==(t=e.target.files)?void 0:t[0];e.target.value="",M(r)}}),(0,n.jsx)(L.Button,{type:"button",variant:"outline",disabled:j,onClick:()=>{var e;
1return null==(e=k.current)?void 0:e.click()},children:j?"Uploading…":"Select files"}),(0,n.jsx)("p",{className:"text-xs text-muted-foreground",children:"Images are optimized when possible (same as the media library)."})]})}),(0,n.jsx)(rt,{value:"library",className:"m-0 min-h-0 flex-1 overflow-hidden focus-visible:outline-none",children:(0,n.jsx)("div",{className:"max-h-[min(52vh,480px)] overflow-y-auto px-4 py-4",children:C?(0,n.jsx)("p",{className:"py-16 text-center text-sm text-muted-foreground",children:"Loading library…"}):0===E.length?(0,n.jsx)("p",{className:"py-16 text-center text-sm text-muted-foreground",children:0===A.length?"No images yet — use Upload files first.":"No matches."}):(0,n.jsx)("ul",{className:"grid gap-2 [grid-template-columns:repeat(auto-fill,minmax(min(100%,100px),1fr))] sm:gap-3 sm:[grid-template-columns:repeat(auto-fill,minmax(min(100%,120px),1fr))]",children:E.map(e=>{let{objectPath:t,storageUrl:r}=e,a=x===t;return(0,n.jsx)("li",{className:"min-w-0",children:(0,n.jsx)("button",{type:"button",className:"relative w-full overflow-hidden rounded-lg border bg-card text-left shadow-sm outline-none transition hover:border-primary/50 focus-visible:ring-2 focus-visible:ring-ring ".concat(a?"border-primary ring-2 ring-primary":"border-border/80"),onClick:()=>q(t,r),children:(0,n.jsxs)("div",{className:"relative aspect-square bg-muted",children:[(0,n.jsx)("img",{src:r,alt:"",className:"h-full w-full object-cover",loading:"lazy"}),a?(0,n.jsx)("span",{className:"absolute right-1.5 top-1.5 flex h-6 w-6 items-center justify-center rounded-full bg-primary text-primary-foreground shadow",children:(0,n.jsx)(rn.A,{className:"h-3.5 w-3.5",strokeWidth:3})}):null]})})},t)})})})})]}),(0,n.jsxs)(t0,{className:"border-t border-border/80 bg-muted/10 px-5 py-4 sm:justify-between",children:[(0,n.jsx)(L.Button,{type:"button",variant:"ghost",className:"mr-auto",onClick:()=>r(!1),children:"Cancel"}),(0,n.jsx)(L.Button,{type:"button",disabled:!y.trim(),onClick:function(){let e=String(y||"").trim();e&&(null==l||l(e),r(!1))},children:i})]})]})})}function rF(e){let{label:t="Image",bucket:r="cms-uploads",folder:s=eA,value:i,onChange:l,maxWidth:o=1600,maxHeight:d=1600,quality:c=.82,format:u="webp",useMediaPicker:m=!1,mediaPickerTitle:h,mediaPickerConfirmLabel:p="Use image",onEditAttachment:g}=e,[x,f]=(0,a.useState)(!1),[v,y]=(0,a.useState)(""),[j,w]=(0,a.useState)(!1),_=(0,a.useRef)(null),N=(0,a.useMemo)(()=>{if(!i)return"";try{return new URL(i).pathname.split("/").pop()||""}catch(e){return String(i).split("/").pop()||""}},[i]);async function k(e){var t;let n=null==(t=e.target.files)?void 0:t[0];if(n){y(""),f(!0);try{let e="keep"===u?n.type:"jpg"===u?"image/jpeg":"image/webp",t=await rR(n,{maxWidth:o,maxHeight:d,quality:c,mimeType:e,forceTargetMime:"keep"!==u}),a="keep"===u?rD(t.name)||rD(n.name)||"jpg":"jpg"===u?"jpg":"webp",i=eq(n.name,a,s||eA),{error:m}=await T.N.storage.from(r).upload(i,t,{upsert:!0,contentType:t.type||void 0});if(m)throw m;let{data:h}=T.N.storage.from(r).getPublicUrl(i);if(!(null==h?void 0:h.publicUrl))throw Error("Failed to get public URL");null==l||l(h.publicUrl)}catch(e){y((null==e?void 0:e.message)||"Upload failed")}finally{f(!1),e.target.value=""}}}function S(){y(""),null==l||l("")}return(0,n.jsxs)("div",{className:"space-y-2",children:[m?null:(0,n.jsx)("input",{ref:_,type:"file",accept:"image/*",className:"sr-only","aria-hidden":!0,tabIndex:-1,onChange:k,disabled:x}),(0,n.jsx)("p",{className:"text-sm font-medium",children:t}),i?(0,n.jsxs)("div",{className:"group relative overflow-hidden rounded-xl border bg-card",children:[(0,n.jsx)("img",{src:i,alt:N||"Selected image",className:(0,b.cn)("block h-40 w-full object-cover",g&&"cursor-pointer"),title:g?"Click to edit alt text, title, and attachment details":void 0,role:g?"button":void 0,tabIndex:g?0:void 0,onClick:e=>{g&&(e.preventDefault(),g(i))},onKeyDown:e=>{g&&("Enter"===e.key||" "===e.key)&&(e.preventDefault(),g(i))}}),(0,n.jsx)("div",{className:"pointer-events-none absolute inset-0 flex flex-wrap items-center justify-center gap-2 bg-foreground
1/55 opacity-0 transition-opacity duration-200 group-hover:pointer-events-auto group-hover:opacity-100 group-focus-within:pointer-events-auto group-focus-within:opacity-100",role:"presentation",children:m?(0,n.jsxs)(n.Fragment,{children:[g?(0,n.jsxs)(L.Button,{type:"button",variant:"secondary",size:"sm",className:"shadow-md gap-1.5",disabled:x,onClick:()=>g(i),children:[(0,n.jsx)(rO.A,{className:"h-4 w-4 shrink-0","aria-hidden":!0}),"Edit details"]}):null,(0,n.jsx)(L.Button,{type:"button",variant:"secondary",size:"sm",className:"shadow-md",disabled:x,onClick:()=>w(!0),children:"Change image"}),(0,n.jsx)(L.Button,{type:"button",variant:"destructive",size:"sm",className:"shadow-md",disabled:x,onClick:S,children:"Remove"})]}):(0,n.jsxs)(n.Fragment,{children:[g?(0,n.jsxs)(L.Button,{type:"button",variant:"secondary",size:"sm",className:"shadow-md gap-1.5",disabled:x,onClick:()=>g(i),children:[(0,n.jsx)(rO.A,{className:"h-4 w-4 shrink-0","aria-hidden":!0}),"Edit details"]}):null,(0,n.jsx)(L.Button,{type:"button",variant:"secondary",size:"sm",className:"shadow-md",disabled:x,onClick:()=>{var e;return null==(e=_.current)?void 0:e.click()},children:"Change image"}),(0,n.jsx)(L.Button,{type:"button",variant:"destructive",size:"sm",className:"shadow-md",disabled:x,onClick:S,children:"Remove"})]})})]}):null,m?(0,n.jsxs)(n.Fragment,{children:[i?null:(0,n.jsxs)(n.Fragment,{children:[(0,n.jsx)(L.Button,{type:"button",variant:"outline",className:"w-full sm:w-auto",disabled:x,onClick:()=>w(!0),children:"Choose image"}),(0,n.jsx)("p",{className:"text-xs text-muted-foreground",children:"Pick from the media library or upload a new file."})]}),(0,n.jsx)(rB,{open:j,onOpenChange:w,title:null!=h?h:t,confirmLabel:p,onConfirm:e=>null==l?void 0:l(e),uploadMaxWidth:o,uploadMaxHeight:d,uploadQuality:c,uploadFormat:u})]}):i?null:(0,n.jsx)(tR.p,{type:"file",accept:"image/*",onChange:k,disabled:x}),x?(0,n.jsx)("p",{className:"text-xs text-muted-foreground",children:"Uploading…"}):null,v?(0,n.jsx)("p",{className:"text-xs text-destructive",children:v}):null]})}var rU=r(51190),rz=r(63263),rK=r(92925),rG=r(53489),rW=r(13630),rH=r(81288),rV=r(59338);let rQ=new Map,rY={titleMax:100,altMax:160,captionMax:280,descriptionMax:360};function rJ(e,t){let r=String(null!=e?e:"").replace(/\r\n/g,"\n").trim();if(r.length<=t)return r;let n=(r=r.slice(0,t).trim()).lastIndexOf(" ");return n>=Math.floor(.45*t)?r.slice(0,n).trim():r}function r$(e,t){let r=String(null!=e?e:"").replace(/\r?\n/g," ").replace(/\s+/g," ").trim();if(r.length<=t)return r;let n=(r=r.slice(0,t).trim()).lastIndexOf(" ");return n>=Math.floor(.55*t)?r.slice(0,n).trim():r}function rX(e,t){let r=String(null!=e?e:"").replace(/\r\n/g," ").replace(/\s+/g," ").trim();if(!r)return"";let n=r.match(/^[^.!?]+[.!?]?/);return rJ((n?n[0]:r).trim(),t)}async function rZ(e,t){let r=await fetch(e,{mode:"cors",credentials:"omit",signal:t});if(!r.ok)throw Error("Could not load image for AI (".concat(r.status,"). Check that the file URL is reachable."));return r.blob()}async function r0(e){let{apiKey:t,model:r,prompt:n,imageUrl:a,signal:s}=e,i=await rZ(a,s),l=i.type&&"application/octet-stream"!==i.type?i.type:"image/jpeg",o=function(e){let t=new Uint8Array(e),r="";for(let e=0;e<t.length;e+=32768)r+=String.fromCharCode(...t.subarray(e,e+32768));return btoa(r)}(await i.arrayBuffer()),d=new th.ij(t).getGenerativeModel({model:r,generationConfig:{temperature:.25,maxOutputTokens:1500}});return String((await d.generateContent([{text:n},{inlineData:{mimeType:l,data:o}}],{signal:s})).response.text()||"").trim()}async function r1(e){var t,r,n,a;let{baseUrl:s,apiKey:i,model:l,prompt:o,imageUrl:d,extraHeaders:c={},signal:u}=e,m=await fetch("".concat(s,"/chat/completions"),{method:"POST",signal:u,headers:{"Content-Type":"application/json",Authorization:"Bearer ".concat(i),...c},body:JSON.stringify({model:l,temperature:.25,max_tokens:1500,messages:[{role:"user",content:[{type:"text",text:o},{type:"image_url",image_url:{url:d,detail:"low"}}]}]})});if(!m.ok){let e=Error(await m.text()||"".concat(m.status," ").concat(m.statusText));throw e.status=m.status,e}return String(null!=(a=null==(n=(await m.json()).choices)||null==(r=n[0])||null==(t=r.message)?void 0:t.content)?a:"").trim()}async function r2(e,t,r,n,a,s){switch(e){case"gemini":return r0({apiKey:t,model:r,prompt:n,imageUrl:a,signal:s});case"openai":return r1({baseUrl:"https://api.openai.com/v1",apiKey:t,model:r,prompt:n,imageUrl:a,signal:s});case"groq":throw Error("Groq models configured here are text-only. Switch Admin → API Settings default AI to Gemini or OpenAI (e.g. GPT-4o) for image metadata.");case"grok":return r1({baseUrl:"https://api.x.ai/v1",apiKey:t,model:r,prompt:n,imageUrl:a,signal:s});case"openrouter":return r1({baseUrl:"https://openrouter.ai/api/v1",a
1piKey:t,model:r,prompt:n,imageUrl:a,signal:s,extraHeaders:{"HTTP-Referer":eS.W6,"X-Title":"Appar Admin — CMS media meta"}});default:throw Error("Unknown provider: ".concat(e))}}async function r4(e){var t;let r,{provider:n,apiKey:a,apiKeys:s,model:i,imageUrl:l,timeoutMs:o=9e4}=e,d=function(e,t){let r=(Array.isArray(t)?t:[]).map(e=>String(null!=e?e:"").trim()).filter(Boolean);if(r.length)return[...new Set(r)];let n=String(null!=e?e:"").trim();return n?[n]:[]}(a,s);if(!d.length)throw Error("Missing API key — set it in Admin → API Settings.");if(!(null==i?void 0:i.trim()))throw Error("Missing model — choose one in API Settings.");let c=String(l||"").trim();if(!c)throw Error("Missing image URL.");let u='You are a CMS media assistant. Look at the image and return ONLY a single JSON object (no markdown fences, no commentary) with exactly these keys:\n"title", "alt_text", "caption", "description"\n\nStrict length (must not exceed — count spaces):\n- title: one line; max '.concat(rY.titleMax," characters; public SEO title; not a filename.\n- alt_text: ONE short sentence for screen readers; max ").concat(rY.altMax,' characters total; plain facts only; no HTML; no preamble like "Image of".\n- caption: REQUIRED — always a non-empty string. One short line shown under the image (reader-facing, like a photo credit line); can be slightly different wording from the title; max ').concat(rY.captionMax,' characters. Never use "" or null for caption.\n- description: at most 2 short sentences for CMS notes; max ').concat(rY.descriptionMax," characters; plain text, no HTML; stay brief.\n\nDo not pad or over-explain. If unsure, keep alt_text and description shorter rather than longer.\n\nBase all strings ONLY on what is visible in the image. Do not invent brands, numbers, or offers not shown. Escape double quotes inside JSON strings.\n\nPublic image URL (context only, do not paste the URL as the title): ").concat(c),m=d.length,h=null!=(t=rQ.get(n))?t:0;h=(h%m+m)%m;for(let e=0;e<m;e+=1){let t=d[(h+e)%m],{signal:a,cancel:s}=function(e){let t=new AbortController,r=setTimeout(()=>t.abort(),e);return{signal:t.signal,cancel:()=>clearTimeout(r)}}(o);try{let r=await r2(n,t,i,u,c,a);return rQ.set(n,(h+e+1)%m),function(e){var t,r,n,a,s,i,l,o,d;let c,u,m=((u=String(e||"").trim()).startsWith("```")&&(u=u.replace(/^```(?:json)?\s*/i,"").replace(/\s*```\s*$/i,"")),u.trim());try{c=JSON.parse(m)}catch(e){throw Error("Model did not return valid JSON. Try again or pick a vision-capable model.")}if(!c||"object"!=typeof c)throw Error("Invalid JSON shape from model.");let h=r$(null!=(r=null!=(t=c.title)?t:c.Title)?r:"",rY.titleMax),p=rJ(null!=(s=null!=(a=null!=(n=c.alt_text)?n:c.altText)?a:c.alt)?s:"",rY.altMax),g=rJ(null!=(l=null!=(i=c.caption)?i:c.Caption)?l:"",rY.captionMax),x=rJ(null!=(d=null!=(o=c.description)?o:c.Description)?d:"",rY.descriptionMax);if(!g.trim()&&(x.trim()?g=rX(x,rY.captionMax):p.trim()?g=rX(p,rY.captionMax):h.trim()&&(g=r$(h,rY.captionMax))),!h&&!p&&!g&&!x)throw Error("Model returned empty fields.");return{title:h,alt:p,caption:g,description:x}}(r)}catch(t){if(r=(null==t?void 0:t.name)==="AbortError"?Error("Request timed out — try again."):t,!(function(e){var t,r,n,a,s,i,l,o,d,c,u;let m=Number(null!=(d=null!=(o=null!=(l=null!=(i=null!=(s=null==e?void 0:e.status)?s:null==e?void 0:e.statusCode)?i:null==e||null==(t=e.response)?void 0:t.status)?l:null==e||null==(r=e.error)?void 0:r.status)?o:null==e||null==(n=e.cause)?void 0:n.status)?d:NaN);if(429===m||503===m||502===m||408===m||401===m||403===m)return!0;let h="".concat(null!=(c=null==e?void 0:e.message)?c:""," ").concat(null!=(u=null==e||null==(a=e.error)?void 0:a.message)?u:""," ").concat(String(e)).toLowerCase();return!!(/\b429\b/.test(h)||h.includes("rate limit")||h.includes("too many requests")||h.includes("resource exh
1austed")||h.includes("quota")||h.includes("overloaded")||h.includes("unavailable")||h.includes("try again")||h.includes("invalid api key")||h.includes("incorrect api key")||h.includes("api key not valid"))}(t)&&e<m-1))throw r}finally{s()}}throw r||Error("All API keys failed.")}let r5={gemini:[{label:"Gemini 3.1 Flash-Lite",value:"gemini-3.1-flash-lite"},{label:"Gemini 3.1 Flash-Lite Preview",value:"gemini-3.1-flash-lite-preview"},{label:"Gemini 3 Flash Preview",value:"gemini-3-flash-preview"},{label:"Gemini Flash latest",value:"gemini-flash-latest"},{label:"Gemini 2.5 Pro",value:"gemini-2.5-pro"},{label:"Gemini 2.5 Flash",value:"gemini-2.5-flash"},{label:"Gemini 2.5 Flash-Lite",value:"gemini-2.5-flash-lite"},{label:"Gemini 2.5 Flash-Lite Preview (09-2025)",value:"gemini-2.5-flash-lite-preview-09-2025"}],openai:[{label:"GPT-4.1",value:"gpt-4.1"},{label:"GPT-4.1 mini",value:"gpt-4.1-mini"},{label:"GPT-4.1 nano",value:"gpt-4.1-nano"},{label:"GPT-4o",value:"gpt-4o"},{label:"GPT-4o mini",value:"gpt-4o-mini"},{label:"o4-mini",value:"o4-mini"},{label:"o3",value:"o3"},{label:"o3-mini",value:"o3-mini"},{label:"o1",value:"o1"},{label:"o1-mini",value:"o1-mini"},{label:"GPT-4 Turbo",value:"gpt-4-turbo"},{label:"GPT-4",value:"gpt-4"},{label:"GPT-3.5 Turbo",value:"gpt-3.5-turbo"},{label:"ChatGPT-4o",value:"chatgpt-4o-latest"}],openrouter:[{label:"Google Gemini 3.1 Flash-Lite",value:"google/gemini-3.1-flash-lite"},{label:"Google Gemini 3.1 Flash-Lite Preview",value:"google/gemini-3.1-flash-lite-preview"},{label:"Google Gemini 3 Flash Preview",value:"google/gemini-3-flash-preview"},{label:"Google Gemini Flash latest",value:"google/gemini-flash-latest"},{label:"Google Gemini 2.5 Pro",value:"google/gemini-2.5-pro"},{label:"Google Gemini 2.5 Flash",value:"google/gemini-2.5-flash"},{label:"Google Gemini 2.5 Flash-Lite",value:"google/gemini-2.5-flash-lite"},{label:"Google Gemini 2.5 Flash-Lite Preview (09-2025)",value:"google/gemini-2.5-flash-lite-preview-09-2025"},{label:"OpenAI GPT-4o",value:"openai/gpt-4o"},{label:"OpenAI GPT-4o mini",value:"openai/gpt-4o-mini"},{label:"OpenAI o4-mini",value:"openai/o4-mini"},{label:"Anthropic Claude 3.5 Sonnet",value:"anthropic/claude-3.5-sonnet"},{label:"Anthropic Claude 3.7 Sonnet",value:"anthropic/claude-3.7-sonnet"},{label:"Meta Llama 3.3 70B Instruct",value:"meta-llama/llama-3.3-70b-instruct"},{label:"Meta Llama 3.1 70B Instruct",value:"meta-llama/llama-3.1-70b-instruct"},{label:"Meta Llama 3.1 405B Instruct",value:"meta-llama/llama-3.1-405b-instruct"},{label:"DeepSeek V3",value:"deepseek/deepseek-chat"},{label:"DeepSeek R1",value:"deepseek/deepseek-r1"},{label:"Qwen 2.5 72B",value:"qwen/qwen-2.5-72b-instruct"},{label:"Mistral Large",value:"mistralai/mistral-large-2411"},{label:"Cohere Command R+",value:"cohere/command-r-plus-08-2024"}],groq:[{label:"Llama 3.3 70B Versatile",value:"llama-3.3-70b-versatile"},{label:"Llama 3.1 8B Instant",value:"llama-3.1-8b-instant"},{label:"Llama 3.1 70B Versatile",value:"llama-3.1-70b-versatile"},{label:"Llama 3 Groq 70B Tool Use",value:"llama3-groq-70b-8192-tool-use-preview"},{label:"Llama 3 Groq 8B Tool Use",value:"llama3-groq-8b-8192-tool-use-preview"},{label:"Mixtral 8x7B",value:"mixtral-8x7b-32768"},{label:"Gemma 2 9B",value:"gemma2-9b-it"},{label:"Qwen QwQ 32B",value:"qwen-qwq-32b-preview"},{label:"DeepSeek R1 Distill Llama 70B",value:"deepseek-r1-distill-llama-70b"}],grok:[{label:"Grok 2 latest",value:"grok-2-latest"},{label:"Grok 2",value:"grok-2-1212"},{label:"Grok 2 Vision latest",value:"grok-2-vision-latest"},{label:"Grok 2 Vision",value:"grok-2-vision-1212"},{label:"Grok Beta",value:"grok-beta"},{label:"Grok Vision Beta",value:"grok-vision-beta"}]},r3=[{id:"gemini",name:"Google Gemini",keyLabel:"API key (Google AI Studio)",keyPlaceholder:"AIza… or key from Google AI Studio"},{id:"openai",name:"OpenAI",keyLabel:"API key",keyPlaceholder:"sk-… or sk-proj-…"},{id:"openrouter",name:"OpenRouter",keyLabel:"API key",keyPlaceholder:"sk-or-v1-… (OpenRouter)"},{id:"groq",name:"Groq",keyLabel:"API key",keyPlaceholder:"gsk_… (GroqCloud)"},{id:"grok",name:"xAI Grok",keyLabel:"API key (xAI console)",keyPlaceholder:"xai-… or key from xAI"}];function r6(e){var t;return(null==(t=r3.find(t=>
1t.id===e))?void 0:t.name)||e}var r8=r(95704);let r9=Object.fromEntries(r3.map(e=>[e.id,[]])),r7={v:1,internalLinksProvider:"gemini",models:{gemini:"gemini-3.1-flash-lite",openai:"gpt-4o",openrouter:"openai/gpt-4o",groq:"llama-3.3-70b-versatile",grok:"grok-2-latest"},keys:{...r9}},ne=!1,nt=null;function nr(e){if(Array.isArray(e)){let t=[],r=new Set;for(let n of e){let e=String(null!=n?n:"").trim();!e||r.has(e)||(r.add(e),t.push(e))}return t}let t=String(null!=e?e:"").trim();return t?[t]:[]}function nn(e){let t={...r9};for(let r of r3)t[r.id]=nr(null==e?void 0:e[r.id]);return t}function na(){return{...r7,models:{...r7.models},keys:nn({})}}function ns(e){return{...r7,...e,models:{...r7.models,...e.models||{}},keys:nn(e.keys||{})}}function ni(){try{let e=localStorage.getItem("appar_admin_ai_settings_v1");if(!e)return na();let t=JSON.parse(e);return ns(t)}catch(e){return na()}}function nl(){return ne&&null!=nt?ns(nt):ni()}function no(){var e,t,r;let n=nl(),a=n.internalLinksProvider||"gemini",s=nr(null==(e=n.keys)?void 0:e[a]);if(!s.length&&"gemini"===a){let e=String(r8.env.NEXT_PUBLIC_GEMINI_API_KEY||"").trim();e&&(s=[e])}let i=r5[a]||[],l=String((null==(t=n.models)?void 0:t[a])||"").trim(),o=l&&i.some(e=>e.value===l)?l:(null==(r=i[0])?void 0:r.value)||r7.models[a],d=s[0]||"";return{provider:a,apiKeys:s,apiKey:d,model:o}}function nd(){let{apiKeys:e}=no();return e.length>0}function nc(){return{alt:"",title:"",caption:"",description:""}}async function nu(e,t){try{await navigator.clipboard.writeText(e),f({title:"Copied",description:t})}catch(e){f({title:"Could not copy",variant:"destructive"})}}function nm(e){return["admin","cms_media",eC,e]}async function nh(e){if(!e)return null;let{data:t,error:r}=await T.N.from("cms_media").select("title,alt_text,caption,description").eq("bucket",eC).eq("object_path",e).maybeSingle();if(r)throw r;return t}function np(e){var t,r,s;let{open:i,onOpenChange:l,items:d=[],activeIndex:c=0,onActiveIndexChange:u,onRequestDelete:m,onStorageRenamed:h}=e,p=null!=(t=d[c])?t:null,g=(0,o.jE)(),[x,v]=(0,a.useState)(0),[y,b]=(0,a.useState)({w:null,h:null}),[j,w]=(0,a.useState)(nc()),[_,N]=(0,a.useState)(!1),[k,S]=(0,a.useState)(""),C=null!=(r=null==p?void 0:p.objectPath)?r:"",{data:A,isFetching:E}=(0,eK.I)({queryKey:nm(C),queryFn:()=>nh(C),enabled:!!(i&&C),staleTime:15e3});(0,a.useEffect)(()=>{let e=()=>v(e=>e+1);return window.addEventListener("appar-admin-ai-settings",e),()=>window.removeEventListener("appar-admin-ai-settings",e)},[]),(0,a.useEffect)(()=>{(null==p?void 0:p.objectPath)&&(b({w:null,h:null}),w(nc()))},[null==p?void 0:p.objectPath]),(0,a.useEffect)(()=>{var e,t,r,n;if(C&&!E){if(!A)return void w(nc());w({title:null!=(e=A.title)?e:"",alt:null!=(t=A.alt_text)?t:"",caption:null!=(r=A.caption)?r:"",description:null!=(n=A.description)?n:""})}},[C,A,E]);let q=(0,a.useMemo)(()=>nd(),[x]),M=(0,tO.n)({mutationFn:async()=>{var e;let t=String(null!=(e=null==p?void 0:p.storageUrl)?e:"").trim(),{provider:r,apiKeys:n,model:a}=no();return r4({provider:r,apiKeys:n,model:a,imageUrl:t})},onSuccess:e=>{w(t=>({...t,title:e.title,alt:e.alt,caption:e.caption,description:e.description})),f({title:"AI filled fields",description:"Review the text, then click Save details to store it in the database."})},onError:e=>{f({title:"AI fill failed",description:(null==e?void 0:e.message)||"Try another model or check API Settings.",variant:"destructive"})}}),P=(0,tO.n)({mutationFn:async()=>{await eW({objectPath:C,title:j.title,altText:j.alt,caption:j.caption,description:j.description})},onSuccess:()=>{f({title:"Saved",description:"Image details are stored in the database."}),g.invalidateQueries({queryKey:nm(C)}),g.invalidateQueries({queryKey:["admin","cms-media-meta"]})},onError:e=>{f({title:"Save failed",description:(null==e?void 0:e.message)||"Run scripts/ensure-cms-media.sql in Supabase.",variant:"destructive"})}}),I=(0,a.useMemo)(()=>(null==p?void 0:p.objectPath)&&p.objectPath.split("/").pop()||"",[null==p?void 0:p.objectPath]),{fileBaseWithoutExt:O,fileExt:R}=(0,a.useMemo)(()=>{let e=I.lastIndexOf(".");return e<=0?{fileBaseWithoutExt:I,fileExt:""}
1:{fileBaseWithoutExt:I.slice(0,e),fileExt:I.slice(e)}},[I]);(0,a.useEffect)(()=>{N(!1),S("")},[C]);let D=(0,tO.n)({mutationFn:async()=>eJ(C,k,T.N),onSuccess:async e=>{var t;if(e.unchanged)return void f({title:"No change",description:"The name matches the current file (after cleanup)."});N(!1),S(""),await g.refetchQueries({queryKey:["admin","cms-media",eC]});let r=(g.getQueryData(["admin","cms-media",eC])||[]).indexOf(e.newObjectPath);g.removeQueries({queryKey:nm(C)}),await g.invalidateQueries({queryKey:["admin","cms-media-meta"]}),await g.invalidateQueries({queryKey:["public","blog_posts"]}),await g.invalidateQueries({queryKey:["public","blog_post"]}),await g.invalidateQueries({queryKey:["public","page_seo"]}),await g.invalidateQueries({queryKey:["admin","page_seo"]}),await g.invalidateQueries({queryKey:["admin","site_settings"]}),null==h||h(C,e.newObjectPath,r);let n=null!=(t=e.referencesUpdated)?t:0;f({title:"File renamed",description:n>0?"Updated ".concat(n," database row(s) that contained the old image URL (blog content, cover/OG/Twitter images, page SEO, or site defaults)."):"Rename complete. No matching URLs were found in the database (image may not be linked yet, or a different URL format was used)."})},onError:e=>{f({title:"Rename failed",description:(null==e?void 0:e.message)||"Another file may already use this name, or storage policies blocked the move.",variant:"destructive"})}}),B=!!p&&c<d.length-1,F=null!=(s=null==p?void 0:p.storageUrl)?s:"",U=p?function(e){var t;let r=(null==(t=e.split(".").pop())?void 0:t.toLowerCase())||"";return({webp:"image/webp",jpg:"image/jpeg",jpeg:"image/jpeg",png:"image/png",gif:"image/gif",svg:"image/svg+xml"})[r]||"image/".concat(r||"unknown")}(C):"",z=String(j.alt||"").trim();return(0,n.jsx)(tQ,{open:i&&!!p,onOpenChange:l,children:p?(0,n.jsxs)(tX,{className:"flex h-[min(92vh,880px)] w-[min(1180px,calc(100vw-1rem))] max-w-none translate-x-[-50%] translate-y-[-50%] flex-col gap-0 overflow-hidden border-border/80 p-0 shadow-xl sm:rounded-xl",children:[(0,n.jsxs)("div",{className:"flex shrink-0 items-center justify-between gap-3 border-b border-border/80 bg-card px-4 py-3 pr-14",children:[(0,n.jsxs)("div",{className:"min-w-0 pr-2",children:[(0,n.jsx)(t1,{className:"text-left text-base font-semibold sm:text-lg",children:"Attachment details"}),(0,n.jsx)(t2,{className:"sr-only",children:"Preview and edit this image title, alternative text, caption, and description. Copy storage or site URLs, open or download the file, or delete it."})]}),(0,n.jsxs)("div",{className:"flex items-center gap-0.5",children:[(0,n.jsx)(L.Button,{type:"button",variant:"ghost",size:"icon",className:"h-9 w-9 shrink-0",disabled:!(c>0),"aria-label":"Previous attachment",onClick:()=>null==u?void 0:u(c-1),children:(0,n.jsx)(rU.A,{className:"h-5 w-5"})}),(0,n.jsx)(L.Button,{type:"button",variant:"ghost",size:"icon",className:"h-9 w-9 shrink-0",disabled:!B,"aria-label":"Next attachment",onClick:()=>null==u?void 0:u(c+1),children:(0,n.jsx)(rz.A,{className:"h-5 w-5"})})]})]}),(0,n.jsxs)("div",{className:"grid min-h-0 flex-1 lg:grid-cols-[1fr_min(400px,42%)] lg:divide-x lg:divide-border/80",children:[(0,n.jsxs)("div",{className:"flex min-h-[220px] flex-col bg-muted/40 lg:min-h-0",children:[(0,n.jsx)("div",{className:"shrink-0 border-b border-border/60 px-4 py-3 sm:px-5 sm:py-3.5",children:(0,n.jsxs)("div",{className:"grid gap-3 text-sm sm:grid-cols-2 sm:gap-x-6",children:[(0,n.jsx)("div",{className:"sm:col-span-2 space-y-2",children:(0,n.jsxs)("div",{children:[(0,n.jsx)("p",{className:"text-muted-foreground",children:"File name (internal)"}),_?(0,n.jsxs)("div",{className:"mt-2 flex flex-col gap-2 sm:flex-row sm:items-start sm:flex-wrap",children:[(0,n.jsxs)("div",{className:"flex min-w-0 flex-1 items-stretch rounded-md border border-input bg-background shadow-sm focus-within:ring-2 focus-within:ring-ring focus-within:ring-offset-2 ring-offset-background",children:[(0,n.jsx)(tR.p,{id:"media-rename-file",className:"min-w-0 flex-1 border-0 font-mono text-xs shadow-none focus-visible:ring-0 focus-visible:ring-offset-0",value:k,onChange:e=>S(e.target.value),autoComplete:"off",spellCheck:!1,placeholder:"File name","aria-label":"File name without extension"}),R?(0,n.jsx)("span",{className:"flex items-center border-l border-border bg-muted/40 px-2.5 font-mono text-xs text-muted-foreground",children:R}):null]}),(0,n.jsxs)("div",{className:"flex flex-wrap gap-2",children:[(0,n.jsx)(L.Button,{type:"button",size:"sm",className:"shrink-0",disabled:D.isPending||!k.trim()||k.trim()===O,onClick:()=>D.mutate(),children:D.isPending?"Saving…":"Save"}),(0,n.jsx)(L.Button,{type:"button",variant:"ghost",size:"sm",className:"shrink-0",disabled:D.isPending,onClick:()=>{N(!1),S("")},children:"Cancel"})]})]}):(0,n.jsxs)("div",{className:"mt-2 flex flex-wrap items-center gap-2",children:[(0,n.jsx)("p",{className:"min-w-0 flex-1 break-all font-mono text-xs text-foreground",children:I}),(0,n.jsxs)(L.Button,{type:"button",variant:"outline",size:"sm",className:"shrink-0 gap-1.5",onClick:()=>{S(O),N(!0)},children:[(0,n.jsx)(rO.A,{className:"h-3.5 w-3.5"}),"Edit"]})]})]})}),(0,n.jsxs)("div",{children:[(0,n.jsx)("p",{className:"text-muted-foreground",children:"File type"}),(0,n.jsx)("p",{className:"mt-0.5 text-foreground",children:U})]}),(0,n.jsxs)("div",{children:[(0,n.jsx)("p",{className:"text-muted-foreground",children:"Dimensions"}),(0,n.jsx)("p",{className:"mt-0.5 text-foreground",children:null!=y.w&&null!=y.h?"".concat(y.w," \xd7 ").concat(y.h," px"):"—"})]})]})}),(0,n.jsx)("div",{className:"flex min-h-[180px] flex-1 items-center justify-center p-4 sm:min-h-[240px]",children:(0,n.jsx)("img",{src:F,alt:z,className:"max-h-[min(48vh,480px)] max-w-full object-contain shadow-sm",onLoad:e=>{let t=e.currentTarget;
1b({w:t.naturalWidth,h:t.naturalHeight})}})}),(0,n.jsx)("div",{className:"shrink-0 border-t border-border/60 bg-muted/30 px-4 py-3 sm:px-5",children:(0,n.jsxs)("div",{className:"flex w-full flex-wrap items-center justify-between gap-x-2 gap-y-2",children:[(0,n.jsxs)("div",{className:"flex flex-wrap items-center gap-2",children:[(0,n.jsx)(L.Button,{variant:"outline",size:"sm",className:"shrink-0",asChild:!0,children:(0,n.jsxs)("a",{href:F,target:"_blank",rel:"noreferrer",children:[(0,n.jsx)(rK.A,{className:"mr-2 h-4 w-4"}),"Open in new tab"]})}),(0,n.jsx)(L.Button,{variant:"outline",size:"sm",className:"shrink-0",asChild:!0,children:(0,n.jsxs)("a",{href:F,download:I,target:"_blank",rel:"noreferrer",children:[(0,n.jsx)(rG.A,{className:"mr-2 h-4 w-4"}),"Download"]})})]}),(0,n.jsxs)(L.Button,{type:"button",variant:"destructive",size:"sm",className:"shrink-0",onClick:()=>null==m?void 0:m(C),children:[(0,n.jsx)(rW.A,{className:"mr-2 h-4 w-4"}),"Delete permanently"]})]})})]}),(0,n.jsx)("div",{className:"max-h-[45vh] overflow-y-auto border-t border-border/80 p-4 sm:p-5 lg:max-h-none lg:border-t-0",children:(0,n.jsxs)("div",{className:"space-y-4",children:[(0,n.jsxs)("div",{className:"grid gap-2",children:[(0,n.jsx)(tH,{htmlFor:"media-title",children:"Title"}),(0,n.jsx)(tR.p,{id:"media-title",value:j.title,onChange:e=>w(t=>({...t,title:e.target.value})),placeholder:"Public title & SEO (not the storage file name)"})]}),(0,n.jsxs)("div",{className:"grid gap-2",children:[(0,n.jsx)(tH,{htmlFor:"media-alt",children:"Alternative text"}),(0,n.jsx)(rP.T,{id:"media-alt",rows:2,value:j.alt,onChange:e=>w(t=>({...t,alt:e.target.value})),placeholder:"Describe the image for screen readers"})]}),(0,n.jsxs)("div",{className:"grid gap-2",children:[(0,n.jsx)(tH,{htmlFor:"media-caption",children:"Caption"}),(0,n.jsx)(rP.T,{id:"media-caption",rows:2,value:j.caption,onChange:e=>w(t=>({...t,caption:e.target.value}))})]}),(0,n.jsxs)("div",{className:"grid gap-2",children:[(0,n.jsx)(tH,{htmlFor:"media-desc",children:"Description"}),(0,n.jsx)(rP.T,{id:"media-desc",rows:3,value:j.description,onChange:e=>w(t=>({...t,description:e.target.value}))})]}),(0,n.jsxs)("div",{className:"grid gap-2",children:[(0,n.jsx)(tH,{children:"Public file URL"}),(0,n.jsx)(tR.p,{readOnly:!0,value:F,className:"font-mono text-xs"}),(0,n.jsxs)(L.Button,{type:"button",variant:"secondary",size:"sm",className:"w-fit",onClick:()=>nu(F,"Public URL"),children:[(0,n.jsx)(rH.A,{className:"mr-2 h-4 w-4"}),"Copy URL to clipboard"]})]}),(0,n.jsxs)("div",{className:"flex flex-col gap-2 pt-1 sm:flex-row sm:flex-wrap sm:items-center",children:[(0,n.jsxs)(L.Button,{type:"button",variant:"outline",className:"w-full gap-2 sm:w-auto",disabled:M.isPending||!String(F||"").trim()||!q,title:q?void 0:"Add an API key in Admin → API Settings (use a vision model such as Gemini or GPT-4o).",onClick:()=>M.mutate(),children:[(0,n.jsx)(rV.A,{className:"h-4 w-4 shrink-0"}),M.isPending?"Filling…":"AI auto-fill"]}),(0,n.jsx)(L.Button,{type:"button",className:"w-full sm:w-auto",disabled:P.isPending,onClick:()=>P.mutate(),children:P.isPending?"Saving…":"Save details"})]})]})})]})]}):null})}function ng(e){let t=String(null!=e?e:"").trim();if(!t||t.startsWith("#")||t.toLowerCase().startsWith("mailto:"))return null;let r="";try{r=new URL(eS.W6).origin}catch(e){}if(t.startsWith("/"))return"internal";try{let e=new URL(t,eS.W6);if(r&&e.origin===r)return"internal";if(/^https?:/i.test(t))return"external"}catch(e){}return null}function nx(e){let t,r=String(e||"").trim();if(!r||"undefined"==typeof DOMParser)return[];try{t=new DOMParser().parseFromString(r,"text/html")}catch(e){return[]}let n=t.body;if(!n)return[];let a=[];return n.querySelectorAll("a[href]").forEach(e=>{let t=e.getAttribute("href"),r=ng(t);if(!r)return;let n=String(t||"").trim(),s=String(e.textContent||"").replace(/\s+/g," ").trim()||n;a.push({href:n,text:s,kind:r,domIndex:a.length})}),a}function nf(e){let t=new Set,r=[];for(let n of e){let e=ti(n.href)?n.href.split("#")[0].toLowerCase():eX(n.href.startsWith("/")?n.href:"/".concat(n.href));t.has(e)||(t.add(e),r.push({href:n.href,text:n.text,kind:n.kind,removeIndex:n.domIndex}))}return r}let nv=new Map;function ny(e,t){let r=String(null!=e?e:"").trim();return r.length<=t?r:r.slice(0,t).trim()}async function nb(e){let t,{apiKey:r,model:n,prompt:a,signal:s}=e,i=new th.ij(r).getGenerativeModel({model:n,generationConfig:{temperature:.2,maxOutputTokens:8192}});for(let e=1;e<=4;e+=1)try{let e=await i.generateContent(a,{signal:s});return String(e.response.text()||"").trim()}catch(r){if(t=r,!(e<4&&function(e){var t,r,n,a,s,i,l,o,d,c,u;if((null==e?void 0:e.name)==="AbortError")return!1;let m=Number(null!=(d=null!=(o=null!=(l=null!=(i=null!=(s=null==e?void 0:e.status)?s:null==e?void 0:e.statusCode)?i:null==e||null==(t=e.response)?void 0:t.status)?l:null==e||null==(r=e.error)?void 0:r.status)?o:null==e||null==(n=e.cause)?void 0:n.status)?d:NaN);if(429===m||503===m||502===m||408===m)return!0;
1if(401===m||403===m)return!1;let h="".concat(null!=(c=null==e?void 0:e.message)?c:""," ").concat(null!=(u=null==e||null==(a=e.error)?void 0:a.message)?u:""," ").concat(String(e)).toLowerCase();return!!(/\b503\b/.test(h)||/\b502\b/.test(h)||/\b429\b/.test(h)||h.includes("service unavailable")||h.includes("unavailable")||h.includes("overloaded")||h.includes("try again")||h.includes("resource exhausted")||h.includes("econnreset"))}(r)))throw r;await function(e){return new Promise(t=>setTimeout(t,e))}(600*e*e)}throw t}async function nj(e){var t,r,n,a;let{baseUrl:s,apiKey:i,model:l,prompt:o,extraHeaders:d={},signal:c}=e,u=await fetch("".concat(s,"/chat/completions"),{method:"POST",signal:c,headers:{"Content-Type":"application/json",Authorization:"Bearer ".concat(i),...d},body:JSON.stringify({model:l,temperature:.2,max_tokens:8192,messages:[{role:"user",content:o}]})});if(!u.ok){let e=Error(await u.text()||"".concat(u.status," ").concat(u.statusText));throw e.status=u.status,e}return String(null!=(a=null==(n=(await u.json()).choices)||null==(r=n[0])||null==(t=r.message)?void 0:t.content)?a:"").trim()}async function nw(e,t,r,n,a){switch(e){case"gemini":return nb({apiKey:t,model:r,prompt:n,signal:a});case"openai":return nj({baseUrl:"https://api.openai.com/v1",apiKey:t,model:r,prompt:n,signal:a});case"groq":return nj({baseUrl:"https://api.groq.com/openai/v1",apiKey:t,model:r,prompt:n,signal:a});case"grok":return nj({baseUrl:"https://api.x.ai/v1",apiKey:t,model:r,prompt:n,signal:a});case"openrouter":return nj({baseUrl:"https://openrouter.ai/api/v1",apiKey:t,model:r,prompt:n,signal:a,extraHeaders:{"HTTP-Referer":eS.W6,"X-Title":"Appar Admin — SEO health fix"}});default:throw Error("Unknown provider: ".concat(e))}}async function n_(e){var t;let r,{provider:n,apiKey:a,apiKeys:s,model:i,postTitle:l,seo_title:o,seo_description:d,excerpt:c,contentHtml:u,issues:m,hints:h,timeoutMs:p=12e4}=e,g=function(e,t){let r=(Array.isArray(t)?t:[]).map(e=>String(null!=e?e:"").trim()).filter(Boolean);if(r.length)return[...new Set(r)];let n=String(null!=e?e:"").trim();return n?[n]:[]}(a,s);if(!g.length)throw Error("Missing API key — set it in Admin → API Settings.");if(!(null==i?void 0:i.trim()))throw Error("Missing model — choose one in API Settings.");let x=String(l||"").trim(),f=String(o||"").trim(),v=String(d||"").trim(),y=String(c||"").trim(),{html:b,count:j}=function(e){let t,r=String(e||"");if(!r.trim())return{html:r,count:0};try{t=new DOMParser().parseFromString(r,"text/html")}catch(e){return{html:r,count:0}}let n=[...t.querySelectorAll("h1")],a=0;return n.forEach(e=>{var r;let n=t.createElement("h2");n.innerHTML=e.innerHTML,[...e.attributes].forEach(e=>n.setAttribute(e.name,e.value)),null==(r=e.parentNode)||r.replaceChild(n,e),a+=1}),{html:t.body?t.body.innerHTML:r,count:a}}(u||""),w=[];j>0&&w.push("Converted ".concat(j," body <h1> to <h2> (page title stays the only H1)."));let _=b;_.length>12e4&&(_="".concat(_.slice(0,12e4),"\n\n[HTML truncated for AI length.]"));let N=w.join(" "),k=function(e){let{postTitle:t,seoTitleField:r,seoDescriptionField:n,excerptField:a,issues:s,hints:i,htmlForAi:l,deterministicNotes:o}=e,d=s.length?s.map((e,t)=>"".concat(t+1,". ").concat(e)).join("\n"):"(none)",c=i.length?i.map((e,t)=>"".concat(t+1,". ").concat(e)).join("\n"):"(none)";return"You are a CMS SEO repair assistant. The public blog renders the POST TITLE as the ONLY page <h1>. Article body HTML must NOT contain <h1> (use <h2>+ for section headings).\n\nAlready applied automatically before this request:\n".concat(o||"(none)","\n\nCurrent fields:\n- Post title: ").concat(JSON.stringify(t),"\n- SEO title field (may be empty): ").concat(JSON.stringify(r),"\n- Meta description field: ").concat(JSON.stringify(n),"\n- Excerpt field: ").concat(JSON.stringify(a),"\n\nSEO issues to address:\n").concat(d,"\n\nSEO hints (improve if reasonable):\n").concat(c,"\n\nRules:\n- seo_title: max ").concat(tp.seoTitleMax," characters (effective for SERP).\n- seo_description: max ").concat(tp.metaDescriptionMax,' characters; compelling; fix length problems.\n- excerpt: optional; keep under ~2000 characters if you set it.\n- content_html: Return the FULL fixed article HTML only when you change body (e.g. missing img alt, heading levels). If you only adjust meta fields and body is unchanged, omit content_html or set it to null.\n- Do NOT add <h1> in content_html. Use <h2>–<h6> only for headings in the body.\n- For "duplicate SEO title" suggest a unique seo_title that still matches the article.\n- For missing image alt: add concise descriptive alt on <img> tags that lack meaningful alt.\n- CRITICAL — links: Do NOT add, remove, or change any <a href="..."> links in content_html. Preserve every existing anchor exactly (same href, same link text, same placement). Ignore hints about "no internal links" or "no external links" for body HTML — those are fixed manually in the content editor (Add (AI) links, etc.), not by this tool.\n- Do not wrap new text in links and do not insert new URLs.\n\nArticle HTML (after automatic H1→H2 if any):\n').concat(l,'\n\nReturn ONLY a JSON object (no markdown fences) with exactly these keys:\n"changes_summary" (array of short strings: what you changed),\n"seo_title" (string or null if unchanged),\n"seo_description" (string or null),\n"excerpt" (string or null),\n"content_html" (string or null — full HTML when body changed)')}({postTitle:x,seoTitleField:f,seoDescriptionField:v,excerptField:y,issues:m||[],hints:(h||[]).filter(e=>{let t=String(e||"").toLowerCase();return!(/\bno internal links\b/.test(t)||/\bno external links\b/.test(t)||/\blinks?\s+in body\b/.test(t)&&(t.includes("internal")||t.includes("external")))}),htmlForAi:_,deterministicNotes:N}),S=g.length,C=null!=(t=nv.get(n))?t:0;C=(C%S+S)%S;for(let e=0;e<S;e+=1){let t=g[(C+e)%S],{signal:a,cancel:s}=function(e){let t=new AbortController,r=setTimeout(()=>t.abort(),e);return{signal:t.signal,cancel:()=>clearTimeout(r)}}(p);try{let r=await nw(n,t,i,k,a);nv.set(n,(C+e+1)%S);let s=function(e){let t,r,n=((r=String(e||"").trim()).startsWith("```")&&(r=r.replace(/^```(?:json)?\s*/i,"").replace(/\s*```\s*$/i,"")),r.trim());try{t=JSON.parse(n)}catch(e){throw Error("Model did not return valid JSON. Try again or switch model.")}if(!t||"object"!=typeof t)throw Error("Invalid fix JSON.");let a=Array.isArray(t.changes_summary)?t.changes_summary.map(e=>
1String(null!=e?e:"").trim()).filter(Boolean):[],s=null!=t.seo_title?function(e,t){let r=String(e||"").replace(/\r?\n/g," ").replace(/\s+/g," ").trim();if(r.length<=t)return r;let n=(r=r.slice(0,t).trim()).lastIndexOf(" ");return n>=Math.floor(.55*t)?r.slice(0,n).trim():r}(String(t.seo_title),tp.seoTitleMax):null,i=null!=t.seo_description?ny(String(t.seo_description),tp.metaDescriptionMax):null,l=null!=t.excerpt?ny(String(t.excerpt),2e3):null;return{changes_summary:a,seo_title:s,seo_description:i,excerpt:l,content_html:null!=t.content_html?String(t.content_html):null}}(r),l=b;s.content_html&&String(s.content_html).trim()&&(l=String(s.content_html).trim());let o=null!=s.seo_title&&String(s.seo_title).trim()?s.seo_title:f,d=null!=s.seo_description&&String(s.seo_description).trim()?s.seo_description:v,c=null!=s.excerpt&&String(s.excerpt).trim()?s.excerpt:y;return{deterministic_steps:w,ai_summary:s.changes_summary,seo_title:o,seo_description:d,excerpt:c,content_html:l}}catch(t){if(r=(null==t?void 0:t.name)==="AbortError"?Error("Request timed out — try again."):t,!(function(e){var t,r,n,a,s,i,l,o,d,c,u;let m=Number(null!=(d=null!=(o=null!=(l=null!=(i=null!=(s=null==e?void 0:e.status)?s:null==e?void 0:e.statusCode)?i:null==e||null==(t=e.response)?void 0:t.status)?l:null==e||null==(r=e.error)?void 0:r.status)?o:null==e||null==(n=e.cause)?void 0:n.status)?d:NaN);if(429===m||503===m||502===m||408===m||401===m||403===m)return!0;let h="".concat(null!=(c=null==e?void 0:e.message)?c:""," ").concat(null!=(u=null==e||null==(a=e.error)?void 0:a.message)?u:""," ").concat(String(e)).toLowerCase();return!!(/\b429\b/.test(h)||h.includes("rate limit")||h.includes("too many requests")||h.includes("resource exh
1austed")||h.includes("quota")||h.includes("overloaded")||h.includes("unavailable")||h.includes("try again")||h.includes("invalid api key")||h.includes("incorrect api key")||h.includes("api key not valid"))}(t)&&e<S-1))throw r}finally{s()}}throw r||Error("All API keys failed.")}var nN=r(9484);let nk=a.forwardRef((e,t)=>{let{className:r,value:a,...s}=e;return(0,n.jsx)(nN.bL,{ref:t,className:(0,b.cn)("relative h-2 w-full overflow-hidden rounded-full bg-primary/20",r),...s,children:(0,n.jsx)(nN.C1,{className:"h-full w-full flex-1 bg-primary transition-all",style:{transform:"translateX(-".concat(100-(a||0),"%)")}})})});function nS(e){let t,r=JSON.parse(((t=String(e||"").trim()).startsWith("```")&&(t=t.replace(/^```(?:json)?\s*/i,"").replace(/\s*```\s*$/i,"")),t.trim()));if(Array.isArray(r))return{internal:r,external:[]};if(r&&"object"==typeof r)return{internal:Array.isArray(r.internal_links)?r.internal_links:Array.isArray(r.internalLinks)?r.internalLinks:Array.isArray(r.links)?r.links:[],external:[r.external_links,r.externalLinks,r.external].filter(Array.isArray).flat()};throw Error("Expected JSON with internal_links / external_links, a links array, or a root array")}nk.displayName=nN.bL.displayName;let nC=new Map;async function nA(e){let{apiKey:t,model:r,prompt:n}=e,a=new th.ij(t).getGenerativeModel({model:r,generationConfig:{temperature:.2,maxOutputTokens:8192,responseMimeType:"application/json"}});return nS((await a.generateContent(n)).response.text())}async function nE(e){var t,r,n,a;let{baseUrl:s,apiKey:i,model:l,prompt:o,extraHeaders:d={}}=e,c=await fetch("".concat(s,"/chat/completions"),{method:"POST",headers:{"Content-Type":"application/json",Authorization:"Bearer ".concat(i),...d},body:JSON.stringify({model:l,temperature:.2,max_tokens:8192,messages:[{role:"user",content:o}]})});if(!c.ok){let e=Error(await c.text()||"".concat(c.status," ").concat(c.statusText));throw e.status=c.status,e}return nS(null!=(a=null==(n=(await c.json()).choices)||null==(r=n[0])||null==(t=r.message)?void 0:t.content)?a:"")}async function nT(e,t,r,n){switch(e){case"gemini":return nA({apiKey:t,model:r,prompt:n});case"openai":return nE({baseUrl:"https://api.openai.com/v1",apiKey:t,model:r,prompt:n});case"groq":return nE({baseUrl:"https://api.groq.com/openai/v1",apiKey:t,model:r,prompt:n});case"grok":return nE({baseUrl:"https://api.x.ai/v1",apiKey:t,model:r,prompt:n});case"openrouter":return nE({baseUrl:"https://openrouter.ai/api/v1",apiKey:t,model:r,prompt:n,extraHeaders:{"HTTP-Referer":eS.W6,"X-Title":"Appar Admin — internal & external links"}});default:throw Error("Unknown provider: ".concat(e))}}async function nq(e){var t;let r,n,{provider:a,apiKey:s,apiKeys:i,model:l,plainText:o,targets:d,maxInternal:c,maxExternal:u,excludePathKeys:m=[]}=e,h=function(e,t){let r=(Array.isArray(t)?t:[]).map(e=>String(null!=e?e:"").trim()).filter(Boolean);if(r.length)return[...new Set(r)];let n=String(null!=e?e:"").trim();return n?[n]:[]}(s,i);if(!h.length)throw Error("Missing API key — set it in Admin → API Settings.");if(!(null==l?void 0:l.trim()))throw Error("Missing model — choose one in API Settings.");let p=Math.min(20,Math.max(0,Number(c)||0)),g=Math.min(20,Math.max(0,Number(u)||0));if(p+g<1)throw Error("Set at least one internal or external link to request.");let{catalog:x,articleText:f}=function(e){let{plainText:t,targets:r,excludePathKeys:n}=e,a=new Set(n.map(eX));return{catalog:r.filter(e=>(null==e?void 0:e.path)&&!a.has(eX(e.path))).map(e=>({path:e.path,hints:(e.phrases||[]).filter(Boolean)})),articleText:t.length>2e5?"".concat(t.slice(0,2e5),"\n\n[--- Article truncated for model context; prefer anchors from the text above. ---]"):t,maxArticleCharsUsed:Math.min(t.length,2e5)}}({plainText:o,targets:d,excludePathKeys:m});if(p>0&&!x.length)throw Error("No internal link targets (check sitemap and blog posts).");let v=function(e){let{maxInternal:t,maxExternal:r,catalog:n,articleText:a,siteUrl:s}=e,i=t>0?'internal_links: Array of {"path":"/exact/path/from/urls","anchorText":"verbatim substring from article"}.\n- TARGET LENGTH: The admin asked for exactly '.concat(t," internal link suggestion(s) when possible. Your internal_links array MUST have length = min(").concat(t,", number of strong internal matches you can make from urls[] without valid anchors). If the article and urls[] allow ").concat(t," distinct good matches, internal_links MUST contain ").concat(t," items — do not stop early at 2–3 unless no more valid pairs exist.\n- urls[] is the COMPLETE allowlist: use ONLY paths listed in urls[].path (exact string). Each path at most once.\n- anchorText copied verbatim from the article (contiguous). Prefer 2–10 words."):"internal_links: Must be an empty array [].",l=r>0?'external_links: Array of {"url":"https://...","anchorText":"verbatim substring from article"}.\n- TARGET LENGTH: Output up to '.concat(r," external link(s). Your external_links array MUST have length = min(").concat(r,", number of distinct, defensible third-party URLs the article can support). When the text offers enough concepts, you MUST fill all ").concat(r," slots with strong matches — do not stop at 1–2 out of convenience.\n\nE-E-A-T task (use articleText below):\nAnalyze the blog post and suggest high-authority external links that enhance the article's E-E-A-T (Experience, Expertise, Authoritativeness, and Trustworthiness). Treat this like recommending roughly 5–7 excellent sources when the admin quota is that high; always respect maxExternal above as the hard cap.\n\nGuidelines for link selection:\n- Authority first: Prioritize official organizations (.gov, .org), international bodies (UN, WHO, WTO, ICC), world-class research or advisory firms (e.g. McKinsey, Deloitte, Gartner), or well-known educational institutions (.edu).\n- Contextual fit: Suggest links that provide deeper technical definitions, statistical proof, or legal/regulatory standards related to the topic.\n- Non-competitive: Avoid suggesting links to direct competitors of the business, product, or service described 
1in the article.\n- SEO value: Ensure links are highly relevant to the primary and secondary keywords and themes of the post.\n\nHard requirements:\n- Every url MUST be a real, working https URL (canonical official page — verify the path; no invented or placeholder URLs).\n- Do NOT use low-quality blogs, spammy directories, affiliate spam, or unverifiable sources.\n- NEVER put full https URLs in internal_links.\n- Each anchorText must be copied verbatim from the article (contiguous). Each destination URL at most once.\n- No links to ").concat(s,'.\n\nExample shape: {"external_links":[{"url":"https://www.wto.org/english/thewto_e/whatis_e/whatis_e.htm","anchorText":"World Trade Organization"}],"internal_links":[...]}'):"external_links: Must be an empty array [].";return"You are a senior SEO editor for ".concat(eS.W6,".\n\n=== ADMIN QUOTAS (highest priority — follow these counts) ===\n- Internal suggestions requested: ").concat(t," (fill up to this many whenever urls[] + article support it)\n- External suggestions requested: ").concat(r,' (fill up to this many whenever the article has enough distinct anchor opportunities; do not under-deliver out of laziness)\n\nRead the full article, then return ONLY valid JSON:\n{"internal_links":[...],"external_links":[...]}\n\n').concat(i,"\n\n").concat(l,"\n\nAlso in the input JSON below, the fields maxInternal and maxExternal repeat these quotas — they MUST match ").concat(t," and ").concat(r,".\n- urls.length (internal allowlist) = ").concat(n.length,"\n\nInput JSON:\n").concat(JSON.stringify({maxInternal:t,maxExternal:r,urls:n,articleText:a},null,0))}({maxInternal:p,maxExternal:g,catalog:x,articleText:f,siteUrl:eS.W6}),y=h.length,b=null!=(t=nC.get(a))?t:0;b=(b%y+y)%y;for(let e=0;e<y;e+=1){let t=h[(b+e)%y];try{r=await nT(a,t,l,v),nC.set(a,(b+e+1)%y);break}catch(t){if(n=t,!(function(e){var t,r,n,a,s,i,l,o,d,c,u;let m=Number(null!=(d=null!=(o=null!=(l=null!=(i=null!=(s=null==e?void 0:e.status)?s:null==e?void 0:e.statusCode)?i:null==e||null==(t=e.response)?void 0:t.status)?l:null==e||null==(r=e.error)?void 0:r.status)?o:null==e||null==(n=e.cause)?void 0:n.status)?d:NaN);if(429===m||503===m||502===m||408===m||401===m||403===m)return!0;let h="".concat(null!=(c=null==e?void 0:e.message)?c:""," ").concat(null!=(u=null==e||null==(a=e.error)?void 0:a.message)?u:""," ").concat(String(e)).toLowerCase();return!!(/\b429\b/.test(h)||h.includes("rate limit")||h.includes("too many requests")||h.includes("resource exh
1austed")||h.includes("quota")||h.includes("overloaded")||h.includes("unavailable")||h.includes("try again")||h.includes("invalid api key")||h.includes("incorrect api key")||h.includes("api key not valid"))}(t)&&e<y-1))throw t}}if(!r)throw n||Error("All API keys failed.");let j=r.internal||[],w=[...r.external||[]],_=function(e){let t=[],r=[];for(let n of e||[]){if(!n||"object"!=typeof n)continue;let e=String(n.anchorText||n.anchor||"").trim(),a=String(n.url||n.href||n.path||"").trim();ti(a)?e.length>=3&&r.push({url:a,anchorText:e}):t.push(n)}return{internal:t,external:r}}(j);return j=_.internal,w=[...w,..._.external],{internal:p>0?(function(e,t){let r=[],n=new Set;for(let a of e){let e=String((null==a?void 0:a.anchorText)||(null==a?void 0:a.anchor)||"").trim();if(!e)continue;let s=function(e,t){let r=new Set(t.map(e=>eX(e.path))),n=new Map(t.map(e=>[eX(e.path),e.path])),a=function(e){let t=String(e||"").trim();if(!t)return"";try{/^https?:\/\//i.test(t)&&(t=new URL(t).pathname||"/")}catch(e){}let r=t.indexOf("?"),n=t.indexOf("#");return r>
1=0&&(t=t.slice(0,r)),n>=0&&(t=t.slice(0,n)),t.trim()}(e);if(!a.startsWith("/")||a.startsWith("//"))return null;let s=[],i=eX(a);for(let e of(i&&s.push(i),i.startsWith("/m/")&&s.push(eX("/".concat(i.slice(3),"/"))),i.startsWith("/mobile/")&&s.push(eX("/".concat(i.slice(8),"/"))),s))if(e&&r.has(e))return n.get(e)||null;return null}(String((null==a?void 0:a.path)||"").trim(),t);if(!s)continue;let i=eX(s);n.has(i)||(n.add(i),r.push({path:s,anchorText:e}))}return r})(j,x).slice(0,p):[],external:g>0?function(e,t,r){let n="";try{n=new URL(r).origin}catch(e){}let a=[],s=new Set;for(let r of e||[]){if(a.length>=t)break;let e=String((null==r?void 0:r.anchorText)||(null==r?void 0:r.anchor)||"").trim();if(!e)continue;let i=String((null==r?void 0:r.url)||(null==r?void 0:r.href)||(null==r?void 0:r.path)||"").trim();if(!ti(i)||function(e){try{let t=new URL(String(e).trim()).hostname.toLowerCase();return"wikipedia.org"===t||t.endsWith(".wikipedia.org")}catch(e){return!1}}(i))continue;try{let e=new URL(i);if("https:"!==e.protocol&&"http:"!==e.protocol||n&&e.origin===n)continue}catch(e){continue}let l=tl(i);if(!l||s.has(l))continue;s.add(l);let o=i;try{let e=new URL(i);e.hash="",o=e.toString()}catch(e){}a.push({path:o,anchorText:e})}return a}(w,g,eS.W6):[]}}let nM=new Map;async function nP(e){let{apiKey:t,model:r,prompt:n,signal:a}=e,s=new th.ij(t).getGenerativeModel({model:r,generationConfig:{temperature:.35,maxOutputTokens:220}});return String((await s.generateContent(n,{signal:a})).response.text()||"").trim()}async function nI(e){var t,r,n,a;let{baseUrl:s,apiKey:i,model:l,prompt:o,extraHeaders:d={},signal:c}=e,u=await fetch("".concat(s,"/chat/completions"),{method:"POST",signal:c,headers:{"Content-Type":"application/json",Authorization:"Bearer ".concat(i),...d},body:JSON.stringify({model:l,temperature:.35,max_tokens:220,messages:[{role:"user",content:o}]})});if(!u.ok){let e=Error(await u.text()||"".concat(u.status," ").concat(u.statusText));throw e.status=u.status,e}return String(null!=(a=null==(n=(await u.json()).choices)||null==(r=n[0])||null==(t=r.message)?void 0:t.content)?a:"").trim()}async function nL(e,t,r,n,a){switch(e){case"gemini":return nP({apiKey:t,model:r,prompt:n,signal:a});case"openai":return nI({baseUrl:"https://api.openai.com/v1",apiKey:t,model:r,prompt:n,signal:a});case"groq":return nI({baseUrl:"https://api.groq.com/openai/v1",apiKey:t,model:r,prompt:n,signal:a});case"grok":return nI({baseUrl:"https://api.x.ai/v1",apiKey:t,model:r,prompt:n,signal:a});case"openrouter":return nI({baseUrl:"https://openrouter.ai/api/v1",apiKey:t,model:r,prompt:n,signal:a,extraHeaders:{"HTTP-Referer":eS.W6,"X-Title":"Appar Admin — excerpt"}});default:throw Error("Unknown provider: ".concat(e))}}async function nO(e){var t;let r,{provider:n,apiKey:a,apiKeys:s,model:i,htmlContent:l,timeoutMs:o=6e4}=e,d=function(e,t){let r=(Array.isArray(t)?t:[]).map(e=>String(null!=e?e:"").trim()).filter(Boolean);if(r.length)return[...new Set(r)];let n=String(null!=e?e:"").trim();return n?[n]:[]}(a,s);if(!d.length)throw Error("Missing API key — set it in Admin → API Settings.");if(!(null==i?void 0:i.trim()))throw Error("Missing model — choose one in API Settings.");let c=String(l||"").replace(/<[^>]+>/g," ").replace(/\s+/g," ").trim();if(c.length<24)throw Error("Add more body content first so the model can summarize the post.");let u=c.length>12e4?"".concat(c.slice(0,12e4),"\n\n[Article truncated for length.]"):c,m="You are an editor. Write ONE plain-text blog excerpt for listing cards and meta descriptions.\n\nStrict rules:\n- Maximum 150 characters (including spaces). Shorter is OK if it reads well.\n- Single line only: no line breaks, no markdown, no bullet characters.\n- Do not wrap the answer in quotation marks.\n- Summarize what the article actually says; do not invent facts or URLs.\n\nArticle:\n".concat(u,"\n\nOutput only the excerpt text, nothing else."),h=d.length,p=null!=(t=nM.get(n))?t:0;p=(p%h+h)%h;for(let e=0;e<h;e+=1){let t=d[(p+e)%h],{signal:a,cancel:s}=function(e){let t=new AbortController,r=setTimeout(()=>t.abort(),e);return{signal:t.signal,cancel:()=>clearTimeout(r)}}(o);try{let r=await nL(n,t,i,m,a);nM.set(n,(p+e+1)%h);let s=function(e){let t=String(e||"").replace(/\r?\n/g," ").replace(/\s+/g," ").trim();if((t=t.replace(/^["'«»]|["'«»]$/g,"").trim()).length<=150)return t;let r=(t=t.slice(0,150).trim()).lastIndexOf(" ");return r>=80?t.slice(0,r).trim():t}(r);if(!s)throw Error("Model returned an empty excerpt.");return s}catch(t){if(r=(null==t?void 0:t.name)==="AbortError"?Error("Request timed out — try again."):t,!(function(e){var t,r,n,a,s,i,l,o,d,c,u;let m=Number(null!=(d=null!=(o=null!=(l=null!=(i=null!=(s=null==e?void 0:e.status)?s:null==e?void 0:e.statusCode)?i:null==e||null==(t=e.response)?void 0:t.status)?l:null==e||null==(r=e.error)?void 0:r.status)?o:null==e||null==(n=e.cause)?void 0:n.status)?d:NaN);if(429===m||503===m||502===m||408===m||401===m||403===m)return!0;let h="".concat(null!=(c=null==e?void 0:e.message)?c:""," ").concat(null!=(u=null==e||null==(a=e.error)?void 0:a.message)?u:""," ").concat(String(e)).toLowerCase();return!!(/\b429\b/.test(h)||h.includes("rate limit")||h.includes("too many requests")||h.includes("resource exh
1austed")||h.includes("quota")||h.includes("overloaded")||h.includes("unavailable")||h.includes("try again")||h.includes("invalid api key")||h.includes("incorrect api key")||h.includes("api key not valid"))}(t)&&e<h-1))throw r}finally{s()}}throw r||Error("All API keys failed.")}let nR=new Map;async function nD(e){let{apiKey:t,model:r,prompt:n,signal:a}=e,s=new th.ij(t).getGenerativeModel({model:r,generationConfig:{temperature:.35,maxOutputTokens:8192}});return String((await s.generateContent(n,{signal:a})).response.text()||"").trim()}async function nB(e){var t,r,n,a;let{baseUrl:s,apiKey:i,model:l,prompt:o,extraHeaders:d={},signal:c}=e,u=await fetch("".concat(s,"/chat/completions"),{method:"POST",signal:c,headers:{"Content-Type":"application/json",Authorization:"Bearer ".concat(i),...d},body:JSON.stringify({model:l,temperature:.35,max_tokens:8192,messages:[{role:"user",content:o}]})});if(!u.ok){let e=Error(await u.text()||"".concat(u.status," ").concat(u.statusText));throw e.status=u.status,e}return String(null!=(a=null==(n=(await u.json()).choices)||null==(r=n[0])||null==(t=r.message)?void 0:t.content)?a:"").trim()}async function nF(e,t,r,n,a){switch(e){case"gemini":return nD({apiKey:t,model:r,prompt:n,signal:a});case"openai":return nB({baseUrl:"https://api.openai.com/v1",apiKey:t,model:r,prompt:n,signal:a});case"groq":return nB({baseUrl:"https://api.groq.com/openai/v1",apiKey:t,model:r,prompt:n,signal:a});case"grok":return nB({baseUrl:"https://api.x.ai/v1",apiKey:t,model:r,prompt:n,signal:a});case"openrouter":return nB({baseUrl:"https://openrouter.ai/api/v1",apiKey:t,model:r,prompt:n,signal:a,extraHeaders:{"HTTP-Referer":eS.W6,"X-Title":"Appar Admin — content transform"}});default:throw Error("Unknown provider: ".concat(e))}}async function nU(e){var t,r;let n,{provider:a,apiKey:s,apiKeys:i,model:l,htmlContent:o,postTitle:d="",mode:c,customInstruction:u="",timeoutMs:m=12e4,selectionFragment:h=!1}=e,p=function(e,t){let r=(Array.isArray(t)?t:[]).map(e=>String(null!=e?e:"").trim()).filter(Boolean);if(r.length)return[...new Set(r)];let n=String(null!=e?e:"").trim();return n?[n]:[]}(s,i);if(!p.length)throw Error("Missing API key — set it in Admin → API Settings.");if(!(null==l?void 0:l.trim()))throw Error("Missing model — choose one in API Settings.");let g=String(o||"");if(!g.trim())throw Error("Add body content first.");let x=/<img\b/i.test(String(g||"")),f=g.length>2e5?"".concat(g.slice(0,2e5),"\n\n\x3c!-- [Truncated for API length; edit long posts in parts or shorten source.] --\x3e"):g,v=function(e){let{postTitle:t,htmlChunk:r,mode:n,customInstruction:a,selectionFragment:s,sourceHasImg:i}=e,l=function(e,t){switch(e){case"format_professional":return'TASK — Professional structure (similar length, \xb115%):\n- Reformat the article for a polished blog: clear heading hierarchy (h2 for main sections, h3/h4 for subsections), well-sized paragraphs, bullet or numbered lists where they help scanning.\n- Fix spacing: avoid stacked <br>; use proper block elements.\n- Keep the same facts and tone; do not invent data, quotes, or links.\n- If SOURCE has <img> tags: preserve each with the exact same src (and alt if present). If SOURCE has NO <img> tags: do NOT add any images, diagrams, figures, or placeholder <img> — text only.\n- Preserve <a href="..."> destinations when still appropriate.\n- If the source contains tables (including inside div.ql-table-embed / .ql-table-shell), keep the same data; you may output clean <table> markup.';case"shorten":return"TASK — Shorten (~25–40% fewer words):\n- Tighten prose; remove redundancy and filler while keeping all key points and structure readable.\n- Keep headings and lists where they still make sense; merge micro-paragraphs when helpful.\n- If SOURCE has images: keep every <img> with the same src. If SOURCE has no <img>: do not add any.\n- Preserve important links. Do not add new facts.";case"expand":return"TASK — Expand (~30–50% more substance):\n- Add useful detail: clearer transitions, short examples in prose where natural, and subsection headings if it helps flow.\n- Stay factual: do not invent statistics, brand claims, or citations.\n- NEVER add <img>, diagrams, charts, figures with media, or placeholder/broken image URLs unless SOURCE already contains <img> with a real src. Do not “suggest” a diagram via HTML — use words only.\n- If SOURCE already has <img> tags: keep them with the same src in your output. Preserve or improve link relevance for existing links only; do not add decorative new links.\n- Maintain a professional editorial tone.";
1case"custom":{let e=String(t||"").trim();if(!e)throw Error("Add custom instructions for this mode.");return"TASK — Custom (follow exactly):\n".concat(e,"\n\nRules: stay factual. If SOURCE has no <img>, do not output any <img> or figure-with-image unless the instruction explicitly asks to add an image with a URL you were given. If SOURCE has <img>, preserve src values unless the instruction says otherwise. Keep or improve link quality; output HTML as specified above.")}default:throw Error("Unknown mode: ".concat(e))}}(n,a);return"You are an expert blog editor for a B2B/manufacturing news site.\n\nPost title (for context only; do not repeat as a fake H1 unless the body should open with it): ".concat(JSON.stringify(t||"Untitled"),"\n\n").concat(l,"\n").concat(s?"\n\nSCOPE — SELECTED FRAGMENT ONLY:\n- SOURCE HTML is only a highlighted portion of a longer post, not the full article.\n- Return ONLY replacement HTML for that same portion (similar scope: e.g. a few paragraphs, one section, one list). Do not output a full post, site chrome, or repeated boilerplate.\n- Do not wrap in <html> or <body>. The CMS will splice your output back into the full document.\n":"","\n\nSTRICT OUTPUT RULES:\n- Return ONLY an HTML fragment for the article body. No <!DOCTYPE>, <html>, <head>, or <body> wrapper.\n- No markdown, no code fences, no commentary before or after the HTML.\n- Allowed tags: p, h1, h2, h3, h4, h5, ul, ol, li, strong, b, em, i, u, s, a (href, title, rel, target), br, blockquote, pre, code, span, div (for Quill table embeds only if needed), table, thead, tbody, tr, th, td, img (src, alt, width, height).\n- Do not use inline scripts or event handlers.\n").concat(i?"- SOURCE includes <img>: preserve every image with the SAME src attribute values; do not swap in new URLs.":"- SOURCE has NO <img> tags: output MUST contain ZERO <img> elements and no figure/embed meant as an image. Never invent “diagram” or “illustration” placeholders — prose only.","\n\nSOURCE HTML:\n").concat(r)}({postTitle:String(d||"").trim(),htmlChunk:f,mode:c,customInstruction:u,selectionFragment:h,sourceHasImg:x}),y=p.length,b=null!=(t=nR.get(a))?t:0;b=(b%y+y)%y;for(let e=0;e<y;e+=1){let t=p[(b+e)%y],{signal:s,cancel:i}=function(e){let t=new AbortController,r=setTimeout(()=>t.abort(),e);return{signal:t.signal,cancel:()=>clearTimeout(r)}}(m);try{let n=await nF(a,t,l,v,s);nR.set(a,(b+e+1)%y);let i=function(e){let t,r=((t=String(e||"").trim()).startsWith("```")&&(t=t.replace(/^```(?:html)?\s*/i,"").replace(/\s*```\s*$/i,"")),t.trim()),n=r.match(/<body[^>]*>([\s\S]*?)<\/body>/i);return n&&(r=n[1].trim()),r=r.replace(/^\uFEFF/,"").trim()}(n);x||(r=i,i=String(r||"").replace(/<img\b[^>]*>/gi,""));let o=i.replace(/<[^>]+>/g," ").replace(/\s+/g," ").trim();if(!o||o.length<12)throw Error("Model returned empty or unusable HTML.");return i}catch(t){if(n=(null==t?void 0:t.name)==="AbortError"?Error("Request timed out — try a shorter article or try again."):t,!(function(e){var t,r,n,a,s,i,l,o,d,c,u;let m=Number(null!=(d=null!=(o=null!=(l=null!=(i=null!=(s=null==e?void 0:e.status)?s:null==e?void 0:e.statusCode)?i:null==e||null==(t=e.response)?void 0:t.status)?l:null==e||null==(r=e.error)?void 0:r.status)?o:null==e||null==(n=e.cause)?void 0:n.status)?d:NaN);if(429===m||503===m||502===m||408===m||401===m||403===m)return!0;let h="".concat(null!=(c=null==e?void 0:e.message)?c:""," ").concat(null!=(u=null==e||null==(a=e.error)?void 0:a.message)?u:""," ").concat(String(e)).toLowerCase();return!!(/\b429\b/.test(h)||h.includes("rate limit")||h.includes("too many requests")||h.includes("resource exh
1austed")||h.includes("quota")||h.includes("overloaded")||h.includes("unavailable")||h.includes("try again")||h.includes("invalid api key")||h.includes("incorrect api key")||h.includes("api key not valid"))}(t)&&e<y-1))throw n}finally{i()}}throw n||Error("All API keys failed.")}function nz(e){return"number"!=typeof e||Number.isNaN(e)?"unknown":e>=200&&e<400?"ok":404===e||410===e||e>=500||e>=400?"bad":"unknown"}async function nK(e,t){let r=String(e||"").trim();try{var n;let{data:e}=await t.auth.getSession(),a=null==e||null==(n=e.session)?void 0:n.access_token;if(!a)return null;let{data:s,error:i}=await t.functions.invoke("verify-external-url",{body:{url:r},headers:{Authorization:"Bearer ".concat(a)}});if(i||s&&"object"==typeof s&&s.error)return null;let l=null==s?void 0:s.http_code;if("number"!=typeof l)return null;return nz(l)}catch(e){return null}}async function nG(e){let{timeoutMs:t=15e3,supabaseClient:r}=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},n=String(e||"").trim();if(!/^https?:\/\//i.test(n))return"bad";let{signal:a,clear:s}=function(e){let t=new AbortController,r=setTimeout(()=>t.abort(),e);return{signal:t.signal,clear:()=>clearTimeout(r)}}(t);try{var i;let e;if(r){let e=await nK(n,r);if(null!=e)return e}let t=await fetch("".concat("https://api.allorigins.win/get?url=").concat(encodeURIComponent(n)),{signal:a,credentials:"omit"});if(!t.ok)return"unknown";try{e=await t.json()}catch(e){return"unknown"}let s=null==e||null==(i=e.status)?void 0:i.http_code;if("number"==typeof s)return nz(s);let l=null==e?void 0:e.contents;if(null==l||""===l)return"unknown";return"ok"}catch(e){return"unknown"}finally{s()}}async function nW(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},{concurrency:r=4,timeoutMs:n=15e3,onProgress:a,supabaseClient:s}=t,i=[...new Set(e.map(e=>String(e||"").trim()).filter(Boolean))],l=new Map,o=0;async function d(){for(;o<i.length;){let e=o;o+=1;let t=i[e],r=await nG(t,{timeoutMs:n,supabaseClient:s});l.set(t,r),null==a||a({completed:l.size,total:i.length})}}let c=Math.min(r,Math.max(1,i.length));return await Promise.all(Array.from({length:c},()=>d())),l}let nH="appar-admin-auto-linking",nV=!1,nQ=null;function nY(){try{let e=localStorage.getItem("appar_admin_auto_linking_v1");if(!e)return{internalLinkSitemapPaste:""};let t=JSON.parse(e);return{internalLinkSitemapPaste:String(t.internalLinkSitemapPaste||"")}}catch(e){return{internalLinkSitemapPaste:""}}}function nJ(){return nV&&null!==nQ?{internalLinkSitemapPaste:nQ}:nY()}let n$=["admin","workspace"],nX="admin_ai_settings, internal_link_sitemap_paste";async function nZ(){let{data:e,error:t}=await T.N.from("site_settings").select(nX).eq("id",1).maybeSingle();if(t)throw t;return e}async function n0(e){let{data:t,error:r}=await T.N.from("site_settings").update({...e,updated_at:new Date().toISOString()}).eq("id",1).select(nX).single();if(r)throw r;return t}function n1(e){ne=!0,nt=(null==e?void 0:e.admin_ai_settings)==null||"object"!=typeof e.admin_ai_settings||Array.isArray(e.admin_ai_settings)?null:e.admin_ai_settings,nV=!0,nQ=e&&"string"==typeof e.internal_link_sitemap_paste?e.internal_link_sitemap_paste:null,window.dispatchEvent(new CustomEvent("appar-admin-ai-settings")),window.dispatchEvent(new Event(nH))}function n2(e){let t=String(e||"").trim();if(!t)return"";try{let e=t.startsWith("//")?new URL("https:".concat(t)):new URL(t,"https://example.org");return e.hash="",e.href}catch(e){return t}}async function n4(e,t){let r=await rR(e,{mimeType:"image/webp",forceTargetMime:!0}),n=rD(r.name)||"webp",a=eT("jpg"===n||"jpeg"===n?"jpg":"png"===n||"gif"===n?n:"webp"),{error:s}=await t.storage.from(eC).upload(a,r,{upsert:!0,contentType:r.type||void 0});if(s)throw s;return eI(a,t)}async function n5(e,t){var r;let n=String(e||"").trim(),a=n.startsWith("//")?"https:".concat(n):n,{data:s}=await t.auth.getSession(),i=null==s||null==(r=s.session)?void 0:r.access_token;if(!i)throw Error("Sign in to import images that block browser downloads (CORS).");let{data:l,error:o}=await t.functions.invoke("import-remote-image",{body:{url:a},headers:{Authorization:"Bearer ".concat(i)}});if(o)throw Error(o.message||"Edge function error");
1if(l&&"object"==typeof l&&l.error)throw Error(String(l.error));if(!l||"string"!=typeof l.base64)throw Error("Invalid response from import-remote-image");let d="string"==typeof l.mimeType&&l.mimeType.startsWith("image/")?l.mimeType:"image/jpeg",c=atob(l.base64),u=new Uint8Array(c.length);for(let e=0;e<c.length;e++)u[e]=c.charCodeAt(e);let m=d.includes("png")?"png":d.includes("jpeg")?"jpg":d.includes("webp")?"webp":d.includes("gif")?"gif":"jpg";return new File([u],"imported.".concat(m),{type:d})}async function n3(e,t){let r=String(e||"").trim(),n=r.startsWith("//")?"https:".concat(r):r;try{let e=await fetch(n,{mode:"cors",credentials:"omit",cache:"no-store"});if(!e.ok)throw Error("HTTP ".concat(e.status));let t=await e.blob(),r=t.type&&t.type.startsWith("image/")?t.type:"image/jpeg",a=r.includes("png")?"png":r.includes("jpeg")?"jpg":r.includes("webp")?"webp":r.includes("gif")?"gif":"jpg";return new File([t],"imported.".concat(a),{type:r})}catch(e){try{return await n5(n,t)}catch(n){let t=e instanceof Error?e.message:String(e),r=n instanceof Error?n.message:String(n);throw Error("".concat(t," \xb7 ").concat(r))}}}function n6(e){if(!e||"string"!=typeof e||"undefined"==typeof DOMParser)return[];try{let t=new DOMParser().parseFromString(e,"text/html"),r=new Set,n=[];return t.querySelectorAll("img[src]").forEach(e=>{let t=e.getAttribute("src")||"";if(!function(e){let t=String(e||"").trim();if(!t||t.startsWith("data:")||t.startsWith("blob:")||eF(t)||t.startsWith("/")&&!t.startsWith("//"))return!1;try{let e=new URL(t.startsWith("//")?"https:".concat(t):t);if(!/^https?:$/i.test(e.protocol))return!1;return!0}catch(e){return!1}}(t))return;let a=n2(t);!a||r.has(a)||(r.add(a),n.push(t.trim()))}),n}catch(e){return[]}}async function n8(e,t){let r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{},n=r.onProgress,a=n6(e);if(!a.length)return{html:e||"",imported:0,failed:[]};let s=new Map,i=[],l=0;for(let e of(null==n||n({completed:0,total:a.length,currentUrl:null}),a)){null==n||n({completed:l,total:a.length,currentUrl:e});try{let r=await n3(e,t),n=await n4(r,t);s.set(n2(e),n)}catch(r){let t=(null==r?void 0:r.message)?String(r.message):"Unknown error";i.push({url:e,error:t})}l+=1,null==n||n({completed:l,total:a.length,currentUrl:null})}if(0===s.size)return{html:e||"",imported:0,failed:i};let o=new DOMParser().parseFromString(e,"text/html");return o.querySelectorAll("img[src]").forEach(e=>{let t=n2(e.getAttribute("src")||""),r=s.get(t);r&&e.setAttribute("src",r)}),{html:o.body.innerHTML,imported:s.size,failed:i}}var n9=r(47650),n7=r(46088);r(82994);var ae=r(93545);function at(e,t){e&&t&&(e.getAttribute("title")||e.setAttribute("title",t),e.getAttribute("aria-label")||e.setAttribute("aria-label",t))}function ar(e){var t;let r=null==(t=e.getModule("toolbar"))?void 0:t.container;if(!r)return;at(r.querySelector("button.ql-bold"),"Bold (Ctrl+B)"),at(r.querySelector("button.ql-italic"),"Italic (Ctrl+I)"),at(r.querySelector("button.ql-underline"),"Underline (Ctrl+U)"),at(r.querySelector("button.ql-strike"),"Strikethrough"),at(r.querySelector("button.ql-blockquote"),"Blockquote"),at(r.querySelector("button.ql-code-block"),"Code block"),at(r.querySelector("button.ql-link"),"Insert link"),at(r.querySelector("button.ql-image"),"Insert image"),at(r.querySelector("button.ql-tableHtml"),"Insert table"),at(r.querySelector("button.ql-clean"),"Remove formatting"),r.querySelectorAll("button.ql-list").forEach(e=>{let t=e.getAttribute("value");"ordered"===t&&at(e,"Numbered list"),"bullet"===t&&at(e,"Bulleted list")});let n=r.querySelector(".ql-picker.ql-header");if(n){at(n.querySelector(".ql-picker-label"),"Paragraph and headings");let e={1:"Heading 1",2:"Heading 2",3:"Heading 3",false:"Normal","":"Normal"};n.querySelectorAll(".ql-picker-item").forEach(t=>{var r,n;let a=t.getAttribute("data-value");at(t,null!=(n=null!=(r=e[a])?r:e[String(a)])?n:"Paragraph")})}let a=r.querySelector(".ql-picker.ql-align");if(a){at(a.querySelector(".ql-picker-label"),"Text alignment");let e={"":"Align left",center:"Align center",right:"Align right",justify:"Justify"};a.querySelectorAll(".ql-picker-item").forEach(t=>{var r,n,a;let s=null!=(r=t.getAttribute("data-value"))?r:"";at(t,null!=(a=null!=(n=e[s])?n:e[String(s)])?a:"Alignment")})}let s=r.querySelector(".ql-picker.ql-color");s&&at(s.querySelector(".ql-picker-label"),"Text color");let i=r.querySelector(".ql-picker.ql-background");i&&at(i.querySelector(".ql-picker-label"),"Highlight / background color"),r.querySelectorAll(".ql-color .ql-picker-item, .ql-background .ql-picker-item").forEach(e
1=>{let t=e.getAttribute("data-value");t&&at(e,"inherit"===t||""===t?"Default":t)})}var an=r(99346);let aa=n7.Ay.import("blots/block/embed"),as={ALLOWED_TAGS:["table","tbody","thead","tfoot","caption","tr","th","td","colgroup","col","br","p","span","div","strong","b","em","i","u","s","strike","a","ul","ol","li"],ALLOWED_ATTR:["colspan","rowspan","class","scope","style","href","target","rel","title","id"],ALLOW_DATA_ATTR:!1};function ai(e,t){let r=Math.min(20,Math.max(1,e)),n=Math.min(20,Math.max(1,t)),a="";for(let e=0;e<r;e+=1){a+="<tr>";for(let e=0;e<n;e+=1)a+="<td><br></td>";a+="</tr>"}return'<table class="ql-table"><tbody>'.concat(a,"</tbody></table>")}class al extends aa{static create(e){let t=super.create(e),r=document.createElement("div");return r.className="ql-table-shell",r.innerHTML=function(e){let t=e$.A.sanitize(String(e||""),as);return t.trim()?t:ai(2,2)}(e),r&&r.querySelectorAll("td, th").forEach(e=>{e.setAttribute("contenteditable","true")}),t.appendChild(r),t}static value(e){let t=e.querySelector(".ql-table-shell");return t?t.innerHTML:""}}al.blotName="tableHtml",al.tagName="div",al.className="ql-table-embed";let ao=!1,ad={ALLOWED_TAGS:["table","tbody","thead","tfoot","tr","th","td","br","p","span","b","strong","i","em"],ALLOWED_ATTR:["colspan","rowspan","class","scope","style"],ALLOW_DATA_ATTR:!1};n7.Ay.register(al,!0),ao=!0;let ac=["blog-quill-body","prose","prose-slate","max-w-none","prose-p:leading-relaxed"];function au(e){var t,r;if(!e)return null;if(null==(t=e.files)?void 0:t.length)for(let t=0;t<e.files.length;t++){let r=e.files[t];if(r.type.startsWith("image/"))return r}if(null==(r=e.items)?void 0:r.length)for(let t=0;t<e.items.length;t++){let r=e.items[t];if("file"===r.kind&&r.type.startsWith("image/")){let e=r.getAsFile();if(e)return e}}return null}async function am(e){let t=await rR(e,{mimeType:"image/webp",forceTargetMime:!0}),r=rD(t.name)||"webp",n=eT("jpg"===r||"jpeg"===r?"jpg":"png"===r||"gif"===r?r:"webp"),{error:a}=await T.N.storage.from(eC).upload(n,t,{upsert:!0,contentType:t.type||void 0});if(a)throw a;return eI(n,T.N)}function ah(e){let{value:t,onChange:r,modules:s,toolbarMountId:i,toolbarGroups:l,className:o,placeholder:d,onRequestImage:c,onRequestInlineImageEdit:u,onClipboardImageUploaded:m,onQuillReady:h,blogBodyTypography:p=!0}=e,g=(0,a.useRef)(null),x=(0,a.useRef)(null),v=(0,a.useRef)(r),y=(0,a.useRef)(s),j=(0,a.useRef)(c),w=(0,a.useRef)(u),_=(0,a.useRef)(m),N=(0,a.useRef)(h),k=(0,a.useRef)(!1),S=(0,a.useRef)(null),C=(0,a.useRef)(i),A=(0,a.useRef)(l),E=(0,a.useRef)(p),[T,q]=(0,a.useState)(!1),[M,P]=(0,a.useState)("3,3"),I=(0,a.useRef)(null),O=(0,a.useRef)(0),R=(0,a.useRef)(()=>{}),D=(0,a.useRef)(()=>{}),[B,F]=(0,a.useState)(null),[U,z]=(0,a.useState)(null);E.current=p,y.current=s,v.current=r,j.current=c,w.current=u,_.current=m,N.current=h,C.current=i,A.current=l;let K=(0,a.useCallback)(()=>{window.clearTimeout(O.current),O.current=window.setTimeout(()=>{F(null),z(null)},160)},[]),G=(0,a.useCallback)(()=>{window.clearTimeout(O.current)},[]);R.current=K,D.current=G,(0,a.useLayoutEffect)(()=>{if(!(null==B?void 0:B.el))return void z(null);let e=B.el,t=()=>{let t=e.getBoundingClientRect();z({top:t.top,left:t.left,width:t.width,height:t.height})};t();let r=new ResizeObserver(t);return r.observe(e),window.addEventListener("scroll",t,!0),window.addEventListener("resize",t),()=>{r.disconnect(),window.removeEventListener("scroll",t,!0),window.removeEventListener("resize",t)}},[B]),(0,a.useEffect)(()=>{var e;if(!g.current||x.current)return;let r=y.current||{toolbar:!0},n=r,a=C.current;if(a){let e=document.getElementById(a),t=A.current;if(!e||!Array.isArray(t))return;e.querySelector(".ql-formats")||(0,ae.u)(e,t),n={...r,toolbar:{container:"#".concat(a),..."object"==typeof r.toolbar&&!Array.isArray(r.toolbar)?r.toolbar:{}}}}let s=new n7.Ay(g.current,{theme:"snow",modules:n,placeholder:d||""});x.current=s,E.current&&s.root.classList.add(...ac);let i=s.root,l=i.focus.bind(i);i.focus=function(e){try{if(null!=e&&"object"==typeof e)return l({...e,preventScroll:!0});return l({preventScroll:!0})}catch(e){return l()}},queueMicrotask(()=>{var e;return null==(e=N.current)?void 0:e.call(N,s)});let o=s.getModule("clipboard");(null==o?void 0:o.addMatcher)&&(o.addMatcher("TABLE",(e,t)=>{let r=e$.A.sanitize(e.outerHTML,as);return(r.trim()||(r=e$.A.sanitize(e.outerHTML,ad)),r.trim())?new an().insert({tableHtml:r}):t}),o.addMatcher(".ql-table-embed",(e,t)=>{let r=e.querySelector(".ql-table-shell"),n=r?r.innerHTML:"",a=e$.A.sanitize(n,as);return(a.trim()||(a=e$.A.sanitize(n,ad)),a.trim())?new an().insert({tableHtml:a}):t}));let c=e=>{var t,r;let n=(null==(t=e.clipboardData)?void 0:t.getData("text/html"))||"";if(/<table[\s>]/i.test(n))return;let a=au(e.clipboardData),i=a?null:function(e){if(!e||!/<img/i.test(e))return null;try{let t=new DOMParser().parseFromString(e,"text/html"),r=[...t.querySelectorAll('img[src^="data:image"]')];if(1!==r.length)return null;let n=t.body.cloneNode(!0);
1if(n.querySelectorAll("img").forEach(e=>e.remove()),(n.textContent||"").replace(/\u00a0/g," ").trim().length>0)return null;let a=r[0].getAttribute("src");return a&&a.startsWith("data:image")?a:null}catch(e){return null}}(n);if(a||i){e.preventDefault(),e.stopImmediatePropagation();let t=s.getSelection(!0),r=t?t.index:s.getLength();(async()=>{try{var e;let t=a;if(!t&&i){let e=await fetch(i).then(e=>e.blob()),r=e.type||"image/png",n=r.includes("png")?"png":r.includes("jpeg")?"jpg":r.includes("webp")?"webp":"png";t=new File([e],"pasted.".concat(n),{type:r})}if(!t)return;let n=await am(t);s.insertEmbed(r,"image",n,"user"),s.setSelection(r+1,0,"silent"),null==(e=_.current)||e.call(_)}catch(e){f({title:"Image upload failed",description:(null==e?void 0:e.message)||"Could not save to storage.",variant:"destructive"})}})();return}let l=function(e){let t=String(e||"").replace(/\r\n/g,"\n").replace(/\r/g,"\n");if(!/\t/.test(t))return"";let r=t.split("\n");for(;r.length&&""===r[r.length-1];)r.pop();if(!r.length)return"";let n=r.map(e=>e.split("	")),a=Math.max(...n.map(e=>e.length),0);if(a<2&&n.length<2)return"";let s=n.map(e=>{let t=[...e];for(;t.length<a;)t.push("");return t}),i="";for(let e of s){for(let t of(i+="<tr>",e))i+="<td><p>".concat(String(t).replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;"),"</p></td>");i+="</tr>"}let l='<table class="ql-table"><tbody>'.concat(i,"</tbody></table>"),o=e$.A.sanitize(l,as);return o.trim()?o:""}((null==(r=e.clipboardData)?void 0:r.getData("text/plain"))||"");if(!l)return;e.preventDefault(),e.stopImmediatePropagation();let o=s.getSelection(!0),d=o?o.index:s.getLength();s.insertEmbed(d,"tableHtml",l,"user"),s.setSelection(d+1,0,"silent")};s.root.addEventListener("paste",c,!0);let u=e=>{var t,r;(null==(r=e.dataTransfer)||null==(t=r.types)?void 0:t.includes("Files"))&&e.preventDefault()},m=e=>{let t=au(e.dataTransfer);if(!t)return;e.preventDefault(),e.stopPropagation();let r=s.getSelection(!0),n=r?r.index:s.getLength();(async()=>{try{var e;let r=await am(t);s.insertEmbed(n,"image",r,"user"),s.setSelection(n+1,0,"silent"),null==(e=_.current)||e.call(_)}catch(e){f({title:"Image upload failed",description:(null==e?void 0:e.message)||"Could not save to storage.",variant:"destructive"})}})()};i.addEventListener("dragover",u),i.addEventListener("drop",m);let h=t||"";if(h)try{s.setContents(s.clipboard.convert({html:h,text:""}),"silent")}catch(e){s.root.innerHTML=h}let p=()=>{if(k.current)return;let e=s.root.innerHTML;S.current=e,v.current(e)};s.on("text-change",p),requestAnimationFrame(()=>{requestAnimationFrame(()=>ar(s))});let b=s.getModule("toolbar"),T=null==b||null==(e=b.container)?void 0:e.querySelector("button.ql-tableHtml");T&&(T.innerHTML='<svg viewBox="0 0 18 18" aria-hidden="true"><rect class="ql-stroke" height="12" width="12" x="3" y="3" fill="none"></rect><line class="ql-stroke" x1="7" x2="7" y1="3" y2="15"></line><line class="ql-stroke" x1="11" x2="11" y1="3" y2="15"></line><line class="ql-stroke" x1="3" x2="15" y1="7" y2="7"></line><line class="ql-stroke" x1="3" x2="15" y1="11" y2="11"></line></svg>'),(null==b?void 0:b.addHandler)&&(b.addHandler("image",()=>{let e=j.current;if(e)return void e(s);let t=window.prompt("Image URL");if(t){let e=s.getSelection(!0),r=e?e.index:s.getLength();s.insertEmbed(r,"image",t,"user"),s.setSelection(r+1,0,"silent")}}),b.addHandler("tableHtml",()=>{P("3,3"),q(!0)}));let M=null==b?void 0:b.container,L=0,B=M&&new MutationObserver(()=>{window.clearTimeout(L),L=window.setTimeout(()=>ar(s),60)});B&&M&&B.observe(M,{childList:!0,subtree:!0});let U=e=>{w.current&&(D.current(),F({el:e}))},K=e=>{let t=e.target;t&&"IMG"===t.nodeName&&U(t)},G=e=>{var t;let r=e.target;if(!r||"IMG"!==r.nodeName)return;let n=e.relatedTarget;n&&(null==(t=I.current)?void 0:t.contains(n))||R.current()},W=e=>{let t=e.target;t&&"IMG"===t.nodeName&&w.current&&U(t)},H=e=>{var t;let r=e.target;!(!(r instanceof Node)||(null==(t=I.current)?void 0:t.contains(r)))&&("IMG"===r.nodeName&&i.contains(r)||(F(null),z(null)))};return i.addEventListener("mouseover",K),i.addEventListener("mouseout",G),i.addEventListener("click",W),document.addEventListener("pointerdown",H,!0),()=>{var e;if(window.clearTimeout(L),window.clearTimeout(O.current),null==B||B.disconnect(),i.removeEventListener("mouseover",K),i.removeEventListener("mouseout",G),i.removeEventListener("click",W),document.removeEventListener("pointerdown",H,!0),k.current=!1,s.root.removeEventListener("paste",c,!0),i.removeEventListener("dragover",u),i.removeEventListener("drop",m),s.off("text-change",p),null==(e=N.current)||e.call(N,null),x.current=null,C.current){let e=document.getElementById(C.current);e&&(e.innerHTML="")}g.current&&(g.current.innerHTML="")}},[]),(0,a.useEffect)(()=>{let e=x.current;if(!e)return;let r=null!=t?t:"";if(e.root.innerHTML===r||null!=S.current&&r===S.current){S.current=null;return}k.current=!0;try{try{let t=(null==r?void 0:r.trim())?r:"<p><br></p>",n=e.clipboard.convert({html:t,text:""});e.setContents(n,"silent")}catch(t){e.root.innerHTML=r||"<p><br></p>"}}finally{k.current=!1,S.current=e.root.innerHTML}},[t]);let W=(0,a.useCallback)(()=>{let e=x.current;if(!e)return void q(!1);let t=M.trim();if(!t)return void q(!1);let{rows:r,cols:n}=function(e){var t,r;let n=String(e||"").split(/[x,\s]+/).map(e=>parseInt(e.trim(),10)).filter(e=>!Number.isNaN(e));return{rows:n[0]||3,cols:null!=(r=null!=(t=n[1])?t:n[0])?r:3}}
1(t),a=ai(r,n),s=e.getSelection(!0),i=s?s.index:e.getLength();e.insertEmbed(i,"tableHtml",a,"user"),e.setSelection(i+1,0,"silent"),q(!1),requestAnimationFrame(()=>e.focus())},[M]),H=(0,a.useCallback)(e=>{q(e),e||P("3,3")},[]);return(0,n.jsxs)("div",{className:(0,b.cn)("admin-blog-quill",o),children:[U&&u&&(0,n9.createPortal)((0,n.jsx)("div",{ref:I,className:"pointer-events-auto z-[100]",style:{position:"fixed",top:U.top+8,left:U.left+U.width-8,transform:"translateX(-100%)"},onMouseEnter:G,onMouseLeave:K,children:(0,n.jsxs)(L.Button,{type:"button",size:"sm",variant:"secondary",className:"h-8 gap-1 border border-border/80 bg-background/95 shadow-md backdrop-blur supports-[backdrop-filter]:bg-background/90",onClick:()=>{let e=null==B?void 0:B.el,t=w.current;t&&e&&t({src:e.src}),F(null),z(null)},children:[(0,n.jsx)(rO.A,{className:"h-3.5 w-3.5","aria-hidden":!0}),"Edit"]})}),document.body),(0,n.jsx)(tQ,{open:T,onOpenChange:H,children:(0,n.jsxs)(tX,{hideCloseButton:!0,className:"max-w-md gap-5 rounded-2xl border border-emerald-900/40 bg-[#0f1412] p-6 text-white shadow-[0_24px_80px_rgba(0,0,0,0.55)] sm:rounded-2xl",children:[(0,n.jsxs)(tZ,{className:"space-y-3 text-left",children:[(0,n.jsx)(t1,{className:"text-lg font-semibold tracking-tight text-white",children:"Insert table"}),(0,n.jsx)(t2,{className:"text-[15px] leading-relaxed text-zinc-200",children:"Table size: rows and columns (e.g. 3,4 or 3x4, max 20 each)"})]}),(0,n.jsx)("input",{type:"text",value:M,onChange:e=>P(e.target.value),onKeyDown:e=>{"Enter"===e.key&&(e.preventDefault(),W())},className:"w-full rounded-xl border border-emerald-400/55 bg-[#0a0e0c] px-3.5 py-2.5 text-[15px] text-white outline-none ring-emerald-400/30 placeholder:text-zinc-600 focus:border-emerald-400/90 focus:ring-2",placeholder:"3,3",autoFocus:!0,"aria-label":"Rows and columns"}),(0,n.jsxs)(t0,{className:"flex !flex-row justify-end gap-3 sm:space-x-0",children:[(0,n.jsx)("button",{type:"button",onClick:()=>H(!1),className:"rounded-full border border-emerald-800/80 bg-emerald-950 px-6 py-2.5 text-sm font-medium text-white transition hover:bg-emerald-900",children:"Cancel"}),(0,n.jsx)("button",{type:"button",onClick:W,className:"rounded-full bg-[#9fe8c8] px-6 py-2.5 text-sm font-semibold text-emerald-950 shadow-sm transition hover:bg-[#b5f0d6]",children:"OK"})]})]})}),(0,n.jsx)("div",{ref:g,className:"min-h-[1px]"})]})}var ap=r(48373),ag=r(60805),ax=r(41922),af=r(32265),av=r(78770),ay=r(84336);function ab(e){return String(e||"").toLowerCase().trim().replace(/['"]/g,"").replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"")}function aj(e,t){var r,n;let{isNew:a,existingSlug:s}=t,i=(null==(r=e.slug)?void 0:r.trim())?ab(e.slug):"";if(i)return i;let l=(null==(n=e.title)?void 0:n.trim())?ab(e.title):"";return l||(!a&&String(s||"").trim()?String(s).trim():"draft-".concat(Date.now().toString(36),"-").concat(Math.random().toString(36).slice(2,8)))}async function aw(e){if(!e)return null;let{data:t,error:r}=await T.N.from("blog_posts").select("*").eq("id",e).single();if(r)throw r;return t}function a_(e){return String(e||"").replace(/<[^>]+>/g," ")}function aN(e){try{return new Date(e).toLocaleString(void 0,{dateStyle:"medium",timeStyle:"short"})}catch(t){return String(e)}}let ak={title:"",slug:"",excerpt:"",category:"",cover_image_url:"",featured:!1,created_by:"",content:"",scheduled_at:"",seo_title:"",seo_description:"",focus_keyword:"",meta_keywords:"",canonical_url:"",robots_index:!0,robots_follow:!0,og_title:"",og_description:"",og_image_url:"",twitter_title:"",twitter_description:"",twitter_image_url:"",seo_schema_type:"BlogPosting"},aS=Object.keys(ak);function aC(e){let t={};for(let r of aS)t[r]=e[r];return JSON.stringify(t)}let aA="admin_blog_draft_new";function aE(e){return"admin_blog_last_db_sync_".concat(e)}let aT="admin_blog_last_local_new";function aq(e){return"admin_blog_last_local_".concat(e)}function aM(e){return"admin_blog_draft_edit_".concat(e)}function aP(e){let t="string"==typeof(null==e?void 0:e.display_name)?e.display_name.trim():"";if(t)return t;let r=(null==e?void 0:e.email)||"",n=r.indexOf("@");return n>0?r.slice(0,n):r||(null==e?void 0:e.id)||""}function aI(e,t,r){let n=String(e.created_by||"").trim();if(!n)return null;let a=t.find(e=>e.id===n);
1return a?aP(a)||null:r&&String(r.created_by||"")===n&&String(r.author_display_name||"").trim()||null}let aL=[[{header:[1,2,3,!1]}],["bold","italic","underline","strike"],[{list:"ordered"},{list:"bullet"}],["blockquote","code-block"],["link","image","tableHtml"],[{align:[]}],[{color:[]},{background:[]}],["clean"]];function aO(e){if(!e)return!1;let t=new Date(e).getTime();return!Number.isNaN(t)&&Date.now()-t<=45e3}function aR(e,t){if(null==e||"string"!=typeof e||!(null==t?void 0:t.length))return e;let r=e;for(let[e,n]of t)e&&n&&e!==n&&r.includes(e)&&(r=r.split(e).join(n));return r}function aD(e,t){return!!e&&!!t&&eF(eB(e)||e)===t}var aB=r(58772),aF=r(12036),aU=r(34358);async function az(){let{data:e}=await T.N.from("page_seo").select("route_path, seo_title, robots_index, robots_follow");return(e||[]).reduce((e,t)=>(e[t.route_path]=t,e),{})}async function aK(){let{data:e}=await T.N.from("page_content").select("route_path").order("route_path");return new Set((e||[]).map(e=>e.route_path))}var aG=r(73180);function aW(e){let t=String(e||"/").trim()||"/";return"/"===t?"/":t.endsWith("/")?t:"".concat(t,"/")}async function aH(e){let t=aW(e),r=function(e){let t=aW(e),r=new Set([t]);if("/"!==t){let e=t.replace(/\/+$/,"");e&&r.add(e)}return t.includes("get-a-quote")&&(r.add("/support/get-quotes/"),r.add("/support/get-quotes")),[...r]}(e),{data:n,error:a}=await T.N.from("page_content").select("route_path, section_key, data").in("route_path",r);if(a)throw a;return function(e,t){let r={};for(let a of e){var n;let e=(n=a.route_path)===t?100:n===("/"!==t&&t.endsWith("/")?t.slice(0,-1):t)?90:t.includes("get-a-quote")&&("/support/get-quotes/"===n||"/support/get-quotes"===n)?50:10,s=r[a.section_key];(!s||e>s.p)&&(r[a.section_key]={data:a.data,p:e})}return Object.fromEntries(Object.entries(r).map(e=>{let[t,r]=e;return[t,r.data]}))}(n||[],t)}async function aV(e,t){let r=Object.entries(t).map(t=>{let[r,n]=t;return{route_path:e,section_key:r,data:n,updated_at:new Date().toISOString()}});if(!r.length)return;let{error:n}=await T.N.from("page_content").upsert(r,{onConflict:"route_path,section_key"});if(n)throw n}function aQ(e){let{fieldDef:t,value:r,onChange:a}=e,{type:s,label:i,key:l}=t;return"image"===s?(0,n.jsxs)("div",{className:"space-y-1",children:[(0,n.jsx)(tH,{className:"text-xs text-muted-foreground",children:i}),(0,n.jsx)(rF,{value:r||"",onChange:a,label:"",useMediaPicker:!0,mediaPickerTitle:i||"Image",mediaPickerConfirmLabel:"Use image"})]}):"textarea"===s?(0,n.jsxs)("div",{className:"space-y-1",children:[(0,n.jsx)(tH,{htmlFor:l,className:"text-xs text-muted-foreground",children:i}),(0,n.jsx)(rP.T,{id:l,value:r||"",onChange:e=>a(e.target.value),rows:3,className:"text-sm"})]}):"url"===s?(0,n.jsxs)("div",{className:"space-y-1",children:[(0,n.jsx)(tH,{htmlFor:l,className:"text-xs text-muted-foreground",children:i}),(0,n.jsx)(tR.p,{id:l,type:"text",value:r||"",onChange:e=>a(e.target.value),placeholder:"https:// or /path/",className:"text-sm font-mono"})]}):(0,n.jsxs)("div",{className:"space-y-1",children:[(0,n.jsx)(tH,{htmlFor:l,className:"text-xs text-muted-foreground",children:i}),(0,n.jsx)(tR.p,{id:l,value:r||"",onChange:e=>a(e.target.value),className:"text-sm"})]})}function aY(e){let{itemFields:t,item:r,onChange:a,onDelete:s,index:i}=e;return(0,n.jsxs)("div",{className:"rounded-xl border border-border bg-background p-4 space-y-3 relative group",children:[(0,n.jsxs)("div",{className:"flex items-center justify-between mb-1",children:[(0,n.jsxs)("span",{className:"text-xs font-medium text-muted-foreground",children:["Item ",i+1]}),(0,n.jsx)(L.Button,{type:"button",size:"icon",variant:"ghost",className:"h-6 w-6 opacity-0 group-hover:opacity-100 transition-opacity text-destructive hover:text-destructive",onClick:s,children:(0,n.jsx)(rW.A,{className:"w-3.5 h-3.5"})})]}),t.map(e=>(0,n.jsx)(aQ,{fieldDef:e,value:r[e.key],onChange:t=>a({...r,[e.key]:t})},e.key))]})}function aJ(e){let{fieldDef:t,value:r=[],onChange:a}=e,{itemFields:s=[],label:i}=t;return(0,n.jsxs)("div",{className:"space-y-2",children:[(0,n.jsx)(tH,{className:"text-xs text-muted-foreground",children:i}),(0,n.jsx)("div",{className:"space-y-2",children:r.map((e,t)=>
1(0,n.jsx)(aY,{index:t,itemFields:s,item:e,onChange:e=>(function(e,t){let n=[...r];n[e]=t,a(n)})(t,e),onDelete:()=>{a(r.filter((e,r)=>r!==t))}},t))}),(0,n.jsxs)(L.Button,{type:"button",variant:"outline",size:"sm",onClick:function(){a([...r,s.reduce((e,t)=>({...e,[t.key]:""}),{})])},className:"w-full gap-2 border-dashed text-muted-foreground hover:text-foreground",children:[(0,n.jsx)(af.A,{className:"w-3.5 h-3.5"}),"Add item"]})]})}function a$(e){let{sectionDef:t,data:r,onChange:s}=e,[i,l]=(0,a.useState)(!0);return(0,n.jsxs)("div",{className:"rounded-2xl border border-border bg-card overflow-hidden",children:[(0,n.jsxs)("button",{type:"button",className:"w-full flex items-center justify-between px-5 py-4 hover:bg-muted/40 transition-colors text-left",onClick:()=>l(e=>!e),children:[(0,n.jsx)("span",{className:"font-medium text-sm",children:t.label}),(0,n.jsx)(U.A,{className:(0,b.cn)("w-4 h-4 text-muted-foreground transition-transform",i&&"rotate-180")})]}),i&&(0,n.jsx)("div",{className:"px-5 pb-5 pt-1 space-y-4 border-t border-border/60",children:t.fields.map(e=>{let t=null==r?void 0:r[e.key],a=t=>s({...r,[e.key]:t});return"array"===e.type?(0,n.jsx)(aJ,{fieldDef:e,value:Array.isArray(t)?t:e.defaults||[],onChange:a},e.key):(0,n.jsx)(aQ,{fieldDef:e,value:t,onChange:a},e.key)})})]})}function aX(e){var t;let{routePath:r,pageDef:s}=e,i=(0,o.jE)(),{data:l,isLoading:d}=(0,eK.I)({queryKey:["admin","page_seo_single",r],queryFn:async()=>{let{data:e}=await T.N.from("page_seo").select("*").eq("route_path",r).maybeSingle();return e||null},enabled:!!r}),[c,u]=(0,a.useState)(null),[m,h]=(0,a.useState)(""),[p,g]=(0,a.useState)(!1);(0,a.useEffect)(()=>{if(void 0!==l){var e,t;u({seo_title:(null==l?void 0:l.seo_title)||"",seo_description:(null==l?void 0:l.seo_description)||"",keywords:(null==l?void 0:l.keywords)||"",focus_keyword:(null==l?void 0:l.focus_keyword)||"",canonical_url:(null==l?void 0:l.canonical_url)||"",og_image_url:(null==l?void 0:l.og_image_url)||"",robots_index:null==(e=null==l?void 0:l.robots_index)||e,robots_follow:null==(t=null==l?void 0:l.robots_follow)||t})}},[l]);let x=(0,tO.n)({mutationFn:async()=>{let{error:e}=await T.N.from("page_seo").upsert({route_path:r,page_name:(null==s?void 0:s.label)||r,seo_title:c.seo_title||null,seo_description:c.seo_description||null,keywords:c.keywords||null,focus_keyword:c.focus_keyword||null,og_image_url:c.og_image_url||null,canonical_url:c.canonical_url||null,robots_index:!!c.robots_index,robots_follow:!!c.robots_follow,updated_at:new Date().toISOString()},{onConflict:"route_path"});if(e)throw e},onSuccess:async()=>{await i.invalidateQueries({queryKey:["admin","page_seo"]}),await i.invalidateQueries({queryKey:["admin","page_seo_single",r]}),await i.invalidateQueries({queryKey:["public","page_seo"]}),f({title:"SEO saved"})}});async function v(){if(!nd())return void h("AI not configured — go to Admin → API Settings and add an API key.");h(""),g(!0);try{let{provider:e,apiKeys:t,model:n}=no(),a=await tN({provider:e,apiKeys:t,model:n,routePath:r,pageName:(null==s?void 0:s.label)||""});u(e=>({...e,seo_title:a.seo_title||e.seo_title,seo_description:a.meta_description||e.seo_description,keywords:a.meta_keywords||e.keywords,focus_keyword:a.focus_keyword||e.focus_keyword}))}catch(e){h((null==e?void 0:e.message)||"AI autofill failed.")}finally{g(!1)}}if(d||!c)return(0,n.jsx)("div",{className:"text-sm text-muted-foreground py-8 text-center",children:"Loading SEO data…"});let y=(e,t)=>u(r=>({...r,[e]:t}));return(0,n.jsxs)("div",{className:"space-y-6",children:[(0,n.jsxs)("div",{className:"grid md:grid-cols-2 gap-6",children:[(0,n.jsxs)("div",{className:"space-y-4",children:[(0,n.jsxs)("div",{className:"grid gap-2",children:[(0,n.jsx)(tH,{children:"SEO title"}),(0,n.jsx)(tR.p,{value:c.seo_title,onChange:e=>y("seo_title",e.target.value)})]}),(0,n.jsxs)("div",{className:"grid gap-2",children:[(0,n.jsx)(tH,{children:"Meta description"}),(0,n.jsx)(rP.T,{value:c.seo_description,onChange:e=>y("seo_description",e.target.value),rows:4})]}),(0,n.jsxs)("div",{className:"grid gap-2",children:[(0,n.jsx)(tH,{children:"Keywords"}),(0,n.jsx)(rP.T,{value:c.keywords,onChange:e=>y("keywords",e.target.value),rows:2,placeholder:"comma, separated"})]}),(0,n.jsxs)("div",{className:"grid gap-2",children:[(0,n.jsx)(tH,{children:"Focus keyword"}),(0,n.jsx)(tR.p,{value:c.focus_keyword,onChange:e=>y("focus_keyword",e.target.value)})]})]}),(0,n.jsxs)("div",{className:"space-y-4",children:[(0,n.jsxs)("div",{className:"grid gap-2",children:[(0,n.jsx)(tH,{children:"Canonical URL (optional)"}),(0,n.jsx)(tR.p,{value:c.canonical_url,onChange:e=>y("canonical_url",e.target.value),placeholder:"https://…"})]}),(0,n.jsx)(rF,{label:"OG image (optional)",value:c.og_image_url,onChange:e=>y("og_image_url",e),useMediaPicker:!0,mediaPickerConfirmLabel:"Use image"}),(0,n.jsxs)("div",{className:"flex items-center justify-between rounded-xl border px-4 py-3",children:[(0,n.jsxs)("div",{children:[(0,n.jsx)("p",{className:"text-sm font-medium",children:"Index"}),(0,n.jsx)("p",{className:"text-xs text-muted-foreground",children:"Allow search engine indexing"})]}),(0,n.jsx)(rL,{checked:!!c.robots_index,onCheckedChange:e=>y("robots_index",e)})]}),(0,n.jsxs)("div",{className:"flex items-center justify-between rounded-xl border px-4 py-3",children:[(0,n.jsxs)("div",{children:[(0,n.jsx)("p",{className:"text-sm font-medium",children:"Follow links"}),(0,n.jsx)("p",{className:"text-xs text-muted-foreground",children:"Allow crawlers to follow links"})]}),(0,n.jsx)(rL,{checked:!!c.robots_follow,onCheckedChange:e=>y("robots_follow",e)})]})]})]}),m?(0,n.jsx)("div",{className:"rounded-lg border border-destructive/30 bg-destructive/10 px-3 py-2 text-sm text-destructive",children:m}):null,x.isError?(0,n.jsxs)("div",{className:"rounded-lg border border-destructive/30 bg-destructive/10 px-3 py-2 text-sm text-destructive",children:["Save failed: ",null==(t=x.error)?void 0:t.message]}):null,(0,n.jsxs)("div",{className:"flex items-center gap-2 pt-2",children:[(0,n.jsx)(L.Button,{type:"button",variant:"outline",onClick:v,disabled:p,className:"mr-auto gap-1.5",children:p?(0,n.jsxs)(n.Fragment,{children:[(0,n.jsx)("span",{className:"inline-block h-3 w-3 animate-spin rounded-full border-2 border-current border-t-transparent"}),"Generating…"]}):"✨ AI Autofill"}),(0,n.jsx)(L.Button,{type:"button",onClick:()=>x.mutate(),disabled:x.isPending,children:x.isPending?"Saving…":"Save SEO"})]})]})}async function aZ(e){let t=T.N.from("product_reviews").select("*").order("created_at",{ascending:!1});e&&"all"!==e&&(t=t.eq("status",e));let{data:r,error:n}=await t;if(n)throw n;return r||[]}function a0(e){return String(e||"").toLowerCase().trim().replace(/['"]/g,"").replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"")}async function a1(){let{data:e,error:t}=await T.N.from("product_tags").select("id, name, slug, description, sort_order, created_at").order("sort_order",{ascending:!0}).order("name",{ascending:!0});if(t)throw t;return e||[]}async function a2(){let{data:e,error:t}=await T.N.from("product_tag_assignments").select("tag_id");if(t)throw t;let r={};for(let t of e||[])r[t.tag_id]=(r[t.tag_id]||0)+1;return r}function a4(e){var t;let{row:r,onCancel:s,onSave:i,isSaving:l}=e,[o,d]=(0,a.useState)(r.name),[c,u]=(0,a.useState)(r.slug),[m,h]=(0,a.useState)(r.de
1scription||""),[p,g]=(0,a.useState)(null!=(t=r.sort_order)?t:0);return(0,n.jsxs)("div",{className:"grid gap-4 pt-2",children:[(0,n.jsxs)("div",{className:"grid gap-2",children:[(0,n.jsx)(tH,{children:"Name"}),(0,n.jsx)(tR.p,{value:o,onChange:e=>d(e.target.value)})]}),(0,n.jsxs)("div",{className:"grid gap-2",children:[(0,n.jsx)(tH,{children:"Slug"}),(0,n.jsx)(tR.p,{value:c,onChange:e=>u(e.target.value),className:"font-mono text-sm"})]}),(0,n.jsxs)("div",{className:"grid gap-2",children:[(0,n.jsx)(tH,{children:"Description"}),(0,n.jsx)(rP.T,{value:m,onChange:e=>h(e.target.value),rows:3})]}),(0,n.jsxs)("div",{className:"grid gap-2",children:[(0,n.jsx)(tH,{children:"Sort"}),(0,n.jsx)(tR.p,{type:"number",value:p,onChange:e=>g(Number(e.target.value)||0)})]}),(0,n.jsxs)("div",{className:"flex justify-end gap-2",children:[(0,n.jsx)(L.Button,{type:"button",variant:"outline",onClick:s,children:"Cancel"}),(0,n.jsx)(L.Button,{type:"button",disabled:l||!o.trim(),onClick:()=>i({name:o.trim(),slug:a0(c)||a0(o),description:m.trim()||null,sort_order:p}),children:l?"Saving…":"Save"})]})]})}function a5(e){return String(e||"").toLowerCase().trim().replace(/['"]/g,"").replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"")}async function a3(){let{data:e,error:t}=await T.N.from("product_brands").select("id, name, slug, parent_slug, description, image_url, sort_order, created_at").order("sort_order",{ascending:!0}).order("name",{ascending:!0});if(t)throw t;return e||[]}async function a6(){let{data:e,error:t}=await T.N.from("product_brand_assignments").select("brand_id");if(t)throw t;let r={};for(let t of e||[])r[t.brand_id]=(r[t.brand_id]||0)+1;return r}function a8(e){var t;let{row:r,parentOptions:s,onCancel:i,onSave:l,isSaving:o}=e,[d,c]=(0,a.useState)(r.name),[u,m]=(0,a.useState)(r.slug),[h,p]=(0,a.useState)(r.parent_slug||""),[g,x]=(0,a.useState)(r.image_url||""),[f,v]=(0,a.useState)(r.description||""),[y,b]=(0,a.useState)(null!=(t=r.sort_order)?t:0);return(0,n.jsxs)("div",{className:"grid gap-4 pt-2",children:[(0,n.jsxs)("div",{className:"grid gap-2",children:[(0,n.jsx)(tH,{children:"Name"}),(0,n.jsx)(tR.p,{value:d,onChange:e=>c(e.target.value)})]}),(0,n.jsxs)("div",{className:"grid gap-2",children:[(0,n.jsx)(tH,{children:"Slug"}),(0,n.jsx)(tR.p,{value:u,onChange:e=>m(e.target.value),className:"font-mono text-sm"})]}),(0,n.jsxs)("div",{className:"grid gap-2",children:[(0,n.jsx)(tH,{children:"Parent"}),(0,n.jsxs)(rl,{value:h||"__none__",onValueChange:e=>p("__none__"===e?"":e),children:[(0,n.jsx)(rd,{children:(0,n.jsx)(ro,{})}),(0,n.jsxs)(rm,{children:[(0,n.jsx)(rh,{value:"__none__",children:"None"}),s.map(e=>(0,n.jsx)(rh,{value:e,children:e},e))]})]})]}),(0,n.jsxs)("div",{className:"grid gap-2",children:[(0,n.jsx)(tH,{children:"Image URL"}),(0,n.jsx)(tR.p,{value:g,onChange:e=>x(e.target.value)})]}),(0,n.jsxs)("div",{className:"grid gap-2",children:[(0,n.jsx)(tH,{children:"Description"}),(0,n.jsx)(rP.T,{value:f,onChange:e=>v(e.target.value),rows:3})]}),(0,n.jsxs)("div",{className:"grid gap-2",children:[(0,n.jsx)(tH,{children:"Sort"}),(0,n.jsx)(tR.p,{type:"number",value:y,onChange:e=>b(Number(e.target.value)||0)})]}),(0,n.jsxs)("div",{className:"flex justify-end gap-2",children:[(0,n.jsx)(L.Button,{type:"button",variant:"outline",onClick:i,children:"Cancel"}),(0,n.jsx)(L.Button,{type:"button",disabled:o||!d.trim(),onClick:()=>l({name:d.trim(),slug:a5(u)||a5(d),parent_slug:h||null,image_url:g.trim()||null,description:f.trim()||null,sort_order:y}),children:o?"Saving…":"Save"})]})]})}var a9=r(3397);async function a7(){let{data:e,error:t}=await T.N.from("product_categories").select("id, name, slug, parent_slug, sort_order, created_at").order("sort_order",{ascending:!0}).order("name",{ascending:!0});if(t)throw t;return e||[]}async function se(e){let{count:t}=await T.N.from("products").select("slug",{count:"exact",head:!0}).eq("parent_category_slug",e),{count:r}=await T.N.from("products").select("slug",{count:"exact",head:!0}).eq("category_slug",e),{count:n}=await T.N.from("products").select("slug",{count:"exact",head:!0}).like("category_slug","".concat(e,"/%"));return(t||0)+(r||0)+(n||0)}async function st(e,t){if(!e||!t||e===t)return;let{error:r}=await T.N.from("products").update({parent_category_slug:t,updated_at:new Date().toISOString()}).eq("parent_category_slug",e);if(r)throw r;let{error:n}=await T.N.from("products").update({category_slug:t,updated_at:new Date().toISOString()}).eq("category_slug",e);if(n)throw n;let{data:a,error:s}=await T.N.from("products").select("slug, category_slug").like("category_slug","".concat(e,"/%"));if(s)throw s;for(let r of a||[]){let n=t+r.category_slug.slice(e.length),{error:a}=await T.N.from("products").update({category_slug:n,updated_at:new Date().toISOString()}).eq("slug",r.slug);
1if(a)throw a}}function sr(e){var t;let{row:r,parentOptions:s,onCancel:i,onSave:l,isSaving:o}=e,[d,c]=(0,a.useState)(r.name),[u,m]=(0,a.useState)(r.slug),[h,p]=(0,a.useState)(r.parent_slug||""),[g,x]=(0,a.useState)(null!=(t=r.sort_order)?t:0);return(0,n.jsxs)("div",{className:"grid gap-4 pt-2",children:[(0,n.jsxs)("div",{className:"grid gap-2",children:[(0,n.jsx)(tH,{htmlFor:"pc-edit-name",children:"Display name"}),(0,n.jsx)(tR.p,{id:"pc-edit-name",value:d,onChange:e=>c(e.target.value)})]}),(0,n.jsxs)("div",{className:"grid gap-2",children:[(0,n.jsx)(tH,{htmlFor:"pc-edit-slug",children:"Slug"}),(0,n.jsx)(tR.p,{id:"pc-edit-slug",value:u,onChange:e=>m(e.target.value),className:"font-mono text-sm"})]}),(0,n.jsxs)("div",{className:"grid gap-2",children:[(0,n.jsx)(tH,{children:"Parent category"}),(0,n.jsxs)(rl,{value:h||"__none__",onValueChange:e=>p("__none__"===e?"":e),children:[(0,n.jsx)(rd,{children:(0,n.jsx)(ro,{placeholder:"Top level"})}),(0,n.jsxs)(rm,{children:[(0,n.jsx)(rh,{value:"__none__",children:"Top level"}),s.map(e=>(0,n.jsx)(rh,{value:e,children:e},e))]})]})]}),(0,n.jsxs)("div",{className:"grid gap-2",children:[(0,n.jsx)(tH,{htmlFor:"pc-edit-sort",children:"Sort order"}),(0,n.jsx)(tR.p,{id:"pc-edit-sort",type:"number",value:g,onChange:e=>x(Number(e.target.value)||0)})]}),(0,n.jsxs)("div",{className:"flex justify-end gap-2",children:[(0,n.jsx)(L.Button,{type:"button",variant:"outline",onClick:i,children:"Cancel"}),(0,n.jsx)(L.Button,{type:"button",disabled:o||!d.trim()||!u.trim(),onClick:()=>l({name:d.trim(),slug:u.trim(),parent_slug:h||null,sort_order:g}),children:o?"Saving…":"Save"})]})]})}var sn=r(36204),sa=r(27142);let ss=Object.entries(a9.oZ).map(e=>{let[t]=e;return t});async function si(){let{data:e,error:t}=await T.N.from("product_tags").select("id, name, slug").order("sort_order").order("name");if(t)throw t;return e||[]}async function sl(){let{data:e,error:t}=await T.N.from("product_brands").select("id, name, slug").order("sort_order").order("name");if(t)throw t;return e||[]}var so=r(92649);function sd(e,t){var r,n,a,s;return{parent:String(null!=(n=null!=(r=null==t?void 0:t.parent_category_slug)?r:null==e?void 0:e.parentCategorySlug)?n:"").trim(),category:String(null!=(s=null!=(a=null==t?void 0:t.category_slug)?a:null==e?void 0:e.categorySlug)?s:"").trim()}}let sc=Object.entries(a9.oZ).map(e=>{let[t,r]=e;return{slug:t,...r}});async function su(){let{data:e,error:t}=await T.N.from("products").select("*");if(t)throw t;return(e||[]).reduce((e,t)=>(e[t.slug]=t,e),{})}async function sm(){let{data:e,error:t}=await T.N.from("product_categories").select("slug, name").order("sort_order",{ascending:!0}).order("name",{ascending:!0});if(t)throw t;return e||[]}var sh=r(21286),sp=r(80839);async function sg(){var e,t;let[r,n,a]=await Promise.all([T.N.from("page_seo").select("id",{count:"exact",head:!0}),T.N.from("redirects").select("id",{count:"exact",head:!0}),T.N.from("site_settings").select("google_verification, bing_verification, yandex_verification, pinterest_verification, ahrefs_verification, baidu_verification, google_analytics_measurement_id").eq("id",1).maybeSingle()]),s=a.data?Object.values(a.data).filter(Boolean).length:0;return{pages:null!=(e=r.count)?e:0,redirects:null!=(t=n.count)?t:0,verificationCount:s,verificationTotal:7}}let sx=[{label:"Pages",description:"Manage SEO title, meta description, robots and OG image for every page route.",icon:sh.A,path:"/admin/pages/",countKey:"pages",countLabel:"pages configured"},{label:"Verification & GA4",description:"GA4 measurement ID (top of page), plus Search Console, Bing, Yandex, Pinterest, and other meta tags.",icon:G.A,path:"/admin/seo/verification/",countKey:"verificationCount",countLabel:e=>"".concat(e.verificationCount," / ").concat(e.verificationTotal," tools connected")},{label:"Redirects",description:"Create 301/302 redirects to fix broken links and guide crawlers.",icon:sp.A,path:"/admin/seo/redirects/",countKey:"redirects",countLabel:"redirects active"}],sf=[{key:"google_verification",label:"Google",metaName:"google-site-verification",link:"https://search.google.com/search-console",linkLabel:"Google Search Console",placeholder:"e.g. abc123XYZ...",hint:"Paste the content value from the HTML tag verification method."},{key:"bing_verification",label:"Bing",metaName:"msvalidate.01",link:"https://www.bing.com/webmasters",linkLabel:"Bing Webmaster Tools",placeholder:"e.g. 1234ABCD...",hint:"Paste the content value from the meta tag option."},{key:"yandex_verification",label:"Yandex",metaName:"yandex-verification",link:"https://webmaster.yandex.com",linkLabel:"Yandex Webmaster Tools",placeholder:"e.g. abcdef123456...",hint:"Paste the verification code from the HTML file or meta tag method."},{key:"pinterest_verification",label:"Pinterest",metaName:"p:domain_verify",link:"https://www.pinterest.com/settings/claim",linkLabel:"Pinterest Settings",placeholder:"e.g. abc123...",hint:"Content value or full meta tag — we extract the code. Injected into index.html from the DB (dev/build/Netlify) for crawlers that skip JS. Refresh View Source after save."},{key:"ahrefs_verification",label:"Ahrefs",metaName:"ahrefs-site-verification",link:"https://app.ahrefs.com/dashboard",linkLabel:"Ahrefs",placeholder:"e.g. abc123...",hint:"Get your verification code from Ahrefs → Site Audit."},{key:"baidu_verification",label:"Baidu",metaName:"baidu-site-verification",link:"https://ziyuan.baidu.com",linkLabel:"Baidu Webmaster Tools",placeholder:"e.g. code123...",hint:"Get your verification code from Baidu Webmaster Tools."}],sv="".concat(sf.map(e=>e.key).join(", "),", google_analytics_measurement_id");async function sy(){let{data:e,error:t}=await T.N.from("site_settings").select(sv).eq("id",1).maybeSingle();if(t)throw t;return null!=e?e:{}}
1function sb(){return{...Object.fromEntries(sf.map(e=>[e.key,""])),google_analytics_measurement_id:""}}async function sj(){let{data:e,error:t}=await T.N.from("redirects").select("*").order("created_at",{ascending:!1});if(t)throw t;return e||[]}function sw(){return{from_path:"",to_path:"",redirect_type:"301"}}var s_=r(55958),sN=r(56397);async function sk(e){try{let t=await e.text();return String(t||"").slice(0,200).trim()||"".concat(e.status," ").concat(e.statusText)}catch(t){return"".concat(e.status," ").concat(e.statusText)}}async function sS(e,t){var r;let n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{},a=null!=(r=n.timeoutMs)?r:14e3,s=String(t||"").trim();if(!s){let e=Error("Empty API key");throw e.code="EMPTY_KEY",e}let{signal:i,cancel:l}=function(e){let t=new AbortController,r=setTimeout(()=>t.abort(),e);return{signal:t.signal,cancel:()=>clearTimeout(r)}}(a);try{switch(e){case"gemini":{let e="https://generativelanguage.googleapis.com/v1/models?key=".concat(encodeURIComponent(s),"&pageSize=1"),t=await fetch(e,{method:"GET",signal:i});if(!t.ok){let e=Error(await sk(t));throw e.status=t.status,e}return}case"openai":{let e=await fetch("https://api.openai.com/v1/models?limit=1",{method:"GET",headers:{Authorization:"Bearer ".concat(s)},signal:i});if(!e.ok){let t=Error(await sk(e));throw t.status=e.status,t}return}case"groq":{let e=await fetch("https://api.groq.com/openai/v1/models",{method:"GET",headers:{Authorization:"Bearer ".concat(s)},signal:i});if(!e.ok){let t=Error(await sk(e));throw t.status=e.status,t}return}case"grok":{let e=await fetch("https://api.x.ai/v1/models",{method:"GET",headers:{Authorization:"Bearer ".concat(s)},signal:i});if(!e.ok){let t=Error(await sk(e));throw t.status=e.status,t}return}case"openrouter":{let e=await fetch("https://openrouter.ai/api/v1/auth/key",{method:"GET",headers:{Authorization:"Bearer ".concat(s)},signal:i});if(!e.ok){let t=Error(await sk(e));throw t.status=e.status,t}return}default:{let t=Error("Unknown provider: ".concat(e));throw t.code="UNKNOWN_PROVIDER",t}}}catch(e){if((null==e?void 0:e.name)==="AbortError"){let e=Error("Request timed out — check the key and your network.");throw e.code="TIMEOUT",e}throw e}finally{l()}}async function sC(e){var t;let r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},n=null!=(t=r.timeoutMs)?t:14e3,a=[];for(let[t,r]of Object.entries(e||{})){let e=Array.isArray(r)?r:[];for(let r=0;r<e.length;r+=1){let s=String(e[r]||"").trim();if(s)try{await sS(t,s,{timeoutMs:n})}catch(n){let e=r6(t);a.push({provider:t,keyIndex:r+1,message:"".concat(e," — key ").concat(r+1,": ").concat((null==n?void 0:n.message)||"Verification failed")})}}}return a.length?{ok:!1,failures:a}:{ok:!0}}let sA=r3.map(e=>e.id);function sE(e,t){var r,n;let a=r5[e]||[],s=t[e];return s&&a.some(e=>e.value===s)?s:null!=(n=null==(r=a[0])?void 0:r.value)?n:""}let sT={general:{tagline:"",site_icon_url:"",admin_email:"",anyone_can_register:!1,default_role:"subscriber",timezone:"UTC",date_format:"F j, Y",date_format_custom:"",time_format:"g:i a",time_format_custom:"",week_starts_on:1},writing:{default_category_name:"",default_category_slug:"",default_post_format:"standard",default_editor:"rich",allow_switch_editor:!1},reading:{homepage_mode:"static",homepage_static_slug:"",posts_page_slug:"",posts_per_page:20,syndication_items:10,feed_display:"full"},discussion:{default_ping_status:!1,default_pingback_flag:!1,default_comment_status:!0,comment_registration:!1,require_name_email:!0,close_comments_for_old_posts:!1,close_comments_days_old:14,thread_comments:!0,thread_comments_depth:5,page_comments:!0,comments_per_page:50,default_comments_page:"newest",comment_order:"asc",comments_notify:!0,moderation_notify:!0,comment_moderation:!1,comment_whitelist_previous:!1,comment_max_links:2,moderation_keys:"",disallowed_keys:"",show_avatars:!0,avatar_rating:"G",avatar_default:"mystery"},media:{thumbnail_size_w:150,thumbnail_size_h:150,thumbnail_crop:!0,medium_size_w:300,medium_size_h:300,large_size_w:1024,large_size_h:1024,uploads_use_yearmonth_folders:!0},permalink:{structure:"postname",custom_structure:"/%postname%/",category_base:"",tag_base:"",product_category_base:"product-category",product_tag_base:"product-tag",product_attribute_base:"",product_brand_base:"brand",product_permalink:"product",product_custom_base:"product/"},privacy:{policy_page_path:"/privacy-policy/"}};function sq(e){return null!=e&&"object"==typeof e&&!Array.isArray(e)}function sM(e){let t=null==e?void 0:e.cms_options;return function e(t,r){if(!sq(t))return sq(r)?{...r}:r;let n={...t};if(!sq(r))return n;for(let a of Object.keys(r)){let s=t[a],i=r[a];void 0!==i&&(sq(s)&&sq(i)?n[a]=e(s,i):n[a]=i)}return n}(sT,"object"!=typeof t||null===t||Array.isArray(t)?{}:t)}async function sP(){let{data:e,error:t}=await T.N.from("site_settings").select("*").eq("id",1).single();if(t)throw t;return e}let sI=[{value:"F j, Y",label:"April 7, 2026"},{value:"Y-m-d",label:"2026-04-07"},{value:"m/d/Y",label:"04/07/2026"},{value:"d/m/Y",label:"07/04/2026"},{value:"custom",label:"Custom"}],sL=[{value:"g:i a",label:"6:26 am"},{value:"g:i A",label:"6:26 AM"},{value:"H:i",label:"06:26"},{value:"custom",label:"Custom"}
1],sO=["UTC","America/New_York","America/Chicago","America/Denver","America/Los_Angeles","Europe/London","Europe/Paris","Asia/Dhaka","Asia/Singapore","Australia/Sydney"];function sR(e){var t,r;let n=sM(e).general;return{site_name:e.site_name||"",site_url:e.site_url||"",default_seo_title:e.default_seo_title||"",default_seo_description:e.default_seo_description||"",default_keywords:e.default_keywords||"",default_og_image:e.default_og_image||"",default_twitter_image:e.default_twitter_image||"",robots_index:null==(t=e.robots_index)||t,robots_follow:null==(r=e.robots_follow)||r,tagline:n.tagline||"",site_icon_url:n.site_icon_url||"",admin_email:n.admin_email||"",anyone_can_register:!!n.anyone_can_register,default_role:n.default_role||"subscriber",timezone:n.timezone||"UTC",date_format:n.date_format||"F j, Y",date_format_custom:n.date_format_custom||"",time_format:n.time_format||"g:i a",time_format_custom:n.time_format_custom||"",week_starts_on:Number(n.week_starts_on)||1}}let sD=(0,s.Eu)((0,n.jsxs)(s.qh,{children:[(0,n.jsx)(s.qh,{path:"/login",element:(0,n.jsx)(function(){let{isAuthenticated:e,isAdmin:t,isLoadingAuth:r,authError:i,loginWithGoogle:l}=I(),o=(0,s.Zp)(),d=(0,s.zy)(),c=(0,a.useMemo)(()=>new URLSearchParams(d.search).get("next")||"/admin",[d.search]),[u,m]=(0,a.useState)(""),[h,p]=(0,a.useState)(!1);async function g(){m(""),p(!0);try{await l({next:c})}catch(e){m((null==e?void 0:e.message)||"Login failed")}finally{p(!1)}}return(0,a.useEffect)(()=>{!r&&e&&t&&o(c,{replace:!0})},[r,e,t,o,c]),(0,n.jsx)("div",{className:"min-h-screen bg-background flex items-center justify-center px-6",children:(0,n.jsxs)("div",{className:"w-full max-w-md border rounded-2xl p-6 bg-card shadow-sm",children:[(0,n.jsx)("h1",{className:"text-2xl font-semibold mb-1",children:"Admin Login"}),(0,n.jsx)("p",{className:"text-sm text-muted-foreground mb-6",children:"Sign in to manage CMS content and SEO."}),u?(0,n.jsx)("div",{className:"mb-4 rounded-lg border border-destructive/30 bg-destructive/10 px-3 py-2 text-sm text-destructive",children:u}):null,u||(null==i?void 0:i.type)!=="not_admin"?null:(0,n.jsx)("div",{className:"mb-4 rounded-lg border border-destructive/30 bg-destructive/10 px-3 py-2 text-sm text-destructive",children:"This Google account is not authorized for admin access."}),(0,n.jsx)(L.Button,{className:"w-full",type:"button",disabled:h||r,onClick:g,children:h?"Redirecting…":"Continue with Google"}),r||!e||t?null:(0,n.jsx)("p",{className:"mt-4 text-sm text-muted-foreground",children:"You are signed in, but your account is not an admin."})]})})},{})}),(0,n.jsx)(s.qh,{path:"/preview/blog/:id",element:(0,n.jsx)(O,{children:(0,n.jsx)(function(){let{id:e}=(0,s.g)(),{data:t,isLoading:r,error:l}=(0,eK.I)({queryKey:["admin","blog_post_preview",e],queryFn:()=>tc(e),enabled:!!e,staleTime:5e3,retry:1}),{data:o=[],isLoading:d}=(0,eK.I)({queryKey:["public","blog_related_preview",null==t?void 0:t.slug,null==t?void 0:t.category],queryFn:()=>td({excludeSlug:null==t?void 0:t.slug,category:null==t?void 0:t.category}),enabled:!!(null==t?void 0:t.slug),staleTime:6e4,retry:1}),c=(0,a.useMemo)(()=>(function(e){let t=String(e||"").trim();return t.startsWith("<")&&t.includes(">")})((null==t?void 0:t.content)||""),[null==t?void 0:t.content]),u=(0,a.useMemo)(()=>c&&(null==t?void 0:t.content)?e$.A.sanitize(String(t.content||"").replace(/<p[^>]*>\s*<br\s*\/?>\s*<\/p>/gi,'<div class="h-2"></div>')):"",[c,null==t?void 0:t.content]),m=(0,a.useMemo)(()=>(function(e){if(!e||"string"!=typeof e||"undefined"==typeof DOMParser)return[];try{let t=new DOMParser().parseFromString(e,"text/html"),r=new Set;return t.querySelectorAll("img[src]").forEach(e=>{let t=eF(e.getAttribute("src")||"");t&&r.add(t)}),[...r]}catch(e){return[]}})(u),[u]),h=(0,a.useMemo)(()=>[...m].sort().join("|"),[m]),{data:p=[]}=(0,eK.I)({queryKey:["public","cms_media_preview",h],queryFn:()=>eG(m),enabled:!!(t&&m.length>0),staleTime:6e4,retry:1}),g=(0,a.useMemo)(()=>(function(e){let t=new Map;for(let r of e||[])(null==r?void 0:r.object_path)&&t.set(r.object_path,r);return t})(p),[p]),x=(0,a.useMemo)(()=>
1{if(!u)return"";let e=function(e){if(!e||"string"!=typeof e)return e||"";if(!eD()||"undefined"==typeof DOMParser)return e;try{let t=new DOMParser().parseFromString(e,"text/html");return t.querySelectorAll("img[src]").forEach(e=>{let t=e.getAttribute("src");if(t){if(eR(t))return void e.remove();e.setAttribute("src",eB(t))}}),t.body.innerHTML}catch(t){return e}}(u);return function(e){let t=String(e||"");if(!t)return t;try{let e=new DOMParser().parseFromString('<div id="rw-ext-href">'.concat(t,"</div>"),"text/html").getElementById("rw-ext-href");if(!e)return t;for(let t of e.querySelectorAll("a[href]")){let e=String(t.getAttribute("href")||"").trim();if(!/^https?:\/\//i.test(e))continue;let r=e0(e);r&&r!==e&&t.setAttribute("href",r)}return e.innerHTML}catch(e){return t}}(e=function(e,t){if(!e||"string"!=typeof e)return e||"";if(!t||"function"!=typeof t.get||"undefined"==typeof DOMParser)return e;try{let r=new DOMParser().parseFromString(e,"text/html");return r.querySelectorAll("img[src]").forEach(e=>{let r=e.getAttribute("src")||"",n=eF(r);if(!n)return;let a=t.get(n);if(!a)return;let s=String(a.alt_text||"").trim(),i=String(a.title||"").trim();e.setAttribute("alt",s),i?e.setAttribute("title",i):e.removeAttribute("title")}),r.body.innerHTML}catch(t){return e}}(e,g))},[u,g]),f=(0,a.useMemo)(()=>t?{...t,image:t.cover_image_url?eB(t.cover_image_url):"https://images.unsplash.com/photo-1558769132-cb1aea458c5e?w=1200&q=80",date:t.published_at?(0,to.GP)(new Date(t.published_at),"MMMM d, yyyy"):"",readTime:function(e){let t=Math.max(1,Math.round(String(e||"").replace(/<[^>]+>/g," ").trim().split(/\s+/).filter(Boolean).length/200));return"".concat(t," min read")}(t.content)}:null,[t]),v=(0,a.useMemo)(()=>{if(!(null==t?void 0:t.slug))return null;let e=ez({siteUrl:eS.W6,siteName:eS.yy,slug:t.slug,post:t});return e?JSON.stringify(e):null},[t]);if(r)return(0,n.jsxs)("div",{className:"min-h-screen bg-background",children:[(0,n.jsx)(ek.A,{}),(0,n.jsx)("div",{className:"max-w-7xl mx-auto px-6 lg:px-8 pt-32 pb-24 text-center",children:(0,n.jsx)("p",{className:"text-muted-foreground",children:"Loading preview…"})})]});if(l||!f)return(0,n.jsxs)("div",{className:"min-h-screen bg-background",children:[(0,n.jsxs)(ew.mg,{children:[(0,n.jsxs)("title",{children:["Preview not found | ",eS.yy]}),(0,n.jsx)("meta",{name:"robots",content:"noindex, nofollow"})]}),(0,n.jsx)(ek.A,{}),(0,n.jsxs)("div",{className:"max-w-7xl mx-auto px-6 lg:px-8 pt-32 pb-24 text-center",children:[(0,n.jsx)("h1",{className:"font-serif text-2xl font-semibold text-foreground mb-4",children:"Preview not found"}),(0,n.jsx)("p",{className:"text-muted-foreground mb-8",children:l?l.message:"This post does not exist or has been removed."}),(0,n.jsx)(i.N_,{to:"/admin/blog/",className:"text-primary font-medium hover:underline",children:"← Back to Admin"})]})]});let y=(f.excerpt||"").slice(0,160),b=String(f.seo_description||"").trim().slice(0,160),j=f.title?"PREVIEW: ".concat(f.title):"PREVIEW",w=String(f.meta_keywords||"").trim(),_=String(f.seo_title||"").trim()||j,N=(b||y).slice(0,160),k=String(f.og_title||"").trim()||_,S=String(f.twitter_title||"").trim()||_,C=(String(f.og_description||"").trim()||b||y).slice(0,160),A=(String(f.twitter_description||"").trim()||b||y).slice(0,160),E=f.image,T=(String(f.og_image_url||"").trim()?eB(f.og_image_url):"")||E,q=(String(f.twitter_image_url||"").trim()?eB(f.twitter_image_url):"")||T,M=String(f.author_display_name||"").trim();return(0,n.jsxs)("div",{className:"min-h-screen bg-background",children:[(0,n.jsxs)(ew.mg,{children:[(0,n.jsx)("title",{children:_}),(0,n.jsx)("meta",{name:"description",content:N}),w?(0,n.jsx)("meta",{name:"keywords",content:w}):null,(0,n.jsx)("meta",{name:"robots",content:"noindex, nofollow"}),M?(0,n.jsx)("meta",{name:"author",content:M}):null,(0,n.jsx)("meta",{name:"publisher",content:eS.yy}),(0,n.jsx)("meta",{property:"og:site_name",content:eS.yy}),M?(0,n.jsx)("meta",{property:"article:author",content:M}):null,(0,n.jsx)("meta",{property:"article:publisher",content:eS.yy}),(0,n.jsx)("meta",{property:"og:title",content:k}),(0,n.jsx)("meta",{property:"og:description",content:C}),(0,n.jsx)("meta",{property:"og:image",content:T}),(0,n.jsx)("meta",{name:"twitter:card",content:"summary_large_image"}),(0,n.jsx)("meta",{name:"twitter:title",content:S}),(0,n.jsx)("meta",{name:"twitter:description",content:A}),(0,n.jsx)("meta",{name:"twitter:image",content:q}),v?(0,n.jsx)("script",{type:"application/ld+json",children:v}):null]}),(0,n.jsx)(ek.A,{}),(0,n.jsx)("div",{className:"max-w-7xl mx-auto px-6 lg:px-8 pt-28",children:(0,n.jsxs)("div",{className:"inline-flex items-center gap-3 rounded-full border bg-card px-4 py-2 text-sm",children:[(0,n.jsx)("span",{className:"font-medium",children:"Preview"}),(0,n.jsx)("span",{className:"text-muted-foreground",children:"Drafts and scheduled posts are visible here."}),f.slug?(0,n.jsx)(i.N_,{to:"/".concat(f.slug,"/"),className:"text-primary font-medium hover:underline",children:"Open public URL"}):null]})}),(0,n.jsxs)("div",{className:"relative h-[55vh] min-h-[400px] overflow-hidden mt-6",children:[(0,n.jsx)("img",{src:f.image,alt:f.title||"",className:"w-full h-full object-cover"}),(0,n.jsx)("div",{className:"absolute inset-0 bg-gradient-to-t from-foreground
1/85 via-foreground/40 to-foreground/20"}),(0,n.jsx)("div",{className:"absolute inset-0 flex items-end",children:(0,n.jsx)("div",{className:"max-w-7xl mx-auto px-6 lg:px-8 pb-14 w-full",children:(0,n.jsxs)(ej.m.div,{initial:{opacity:0,y:20},animate:{opacity:1,y:0},children:[(0,n.jsx)(i.N_,{to:"/admin/blog/",className:"inline-flex items-center gap-2 text-white/60 hover:text-white text-sm mb-6 transition-colors",children:"← Back to Admin"}),(0,n.jsxs)("div",{className:"flex items-center gap-3 mb-4",children:[(0,n.jsx)("span",{className:"px-3 py-1 bg-primary text-primary-foreground text-xs font-medium rounded-full",children:f.category}),(0,n.jsxs)("span",{className:"text-white/60 text-xs flex items-center gap-1",children:[(0,n.jsx)(e_.A,{className:"w-3 h-3"}),f.readTime]}),f.date?(0,n.jsx)("span",{className:"text-white/60 text-xs",children:f.date}):null]}),(0,n.jsx)("h1",{className:"font-serif text-3xl lg:text-5xl font-semibold text-white leading-tight max-w-4xl",children:f.title})]})})})]}),(0,n.jsx)("div",{className:"max-w-7xl mx-auto px-6 lg:px-8 py-16",children:(0,n.jsxs)("div",{className:"grid lg:grid-cols-[1fr_280px] gap-14",children:[(0,n.jsxs)(ej.m.article,{initial:{opacity:0,y:20},animate:{opacity:1,y:0},transition:{delay:.2},className:"w-full max-w-full",children:[String(f.excerpt||"").trim()?(0,n.jsx)("p",{className:"text-xl text-muted-foreground leading-relaxed mb-8 border-l-4 border-primary pl-5 py-1",children:f.excerpt}):null,(0,n.jsx)("div",{className:"space-y-1",children:c?(0,n.jsx)("div",{className:"blog-quill-body prose prose-slate w-full max-w-full prose-p:leading-relaxed",dangerouslySetInnerHTML:{__html:x}}):(f.content||"").trim().split("\n").map((e,t)=>{if(e.startsWith("## "))return(0,n.jsx)("h2",{className:"font-serif text-2xl font-semibold text-foreground mt-10 mb-4",children:e.replace("## ","")},t);if(e.startsWith("**")&&e.endsWith("**"))return(0,n.jsx)("p",{className:"font-semibold text-foreground mt-4 mb-1",children:e.replace(/\*\*/g,"")},t);if(e.startsWith("- **")){let r=e.replace("- ","").split("**").filter(Boolean);return(0,n.jsxs)("li",{className:"text-muted-foreground leading-relaxed ml-4",children:[(0,n.jsx)("strong",{className:"text-foreground",children:r[0]}),r[1]||""]},t)}if(e.startsWith("- "))return(0,n.jsx)("li",{className:"text-muted-foreground leading-relaxed ml-4",children:e.replace("- ","")},t);if(/^\d+\./.test(e)){let r=e.split("**").filter(Boolean);return(0,n.jsx)("li",{className:"text-muted-foreground leading-relaxed ml-4 list-decimal",children:r.length>1?(0,n.jsxs)(n.Fragment,{children:[(0,n.jsx)("strong",{className:"text-foreground",children:r[0].replace(/^\d+\.\s*/,"")}),r[1]]}):r[0]},t)}return""===e.trim()?(0,n.jsx)("br",{},t):(0,n.jsx)("p",{className:"text-muted-foreground leading-relaxed",children:e},t)})})]}),(0,n.jsxs)(ej.m.aside,{initial:{opacity:0,x:20},animate:{opacity:1,x:0},transition:{delay:.3},className:"space-y-8",children:[(0,n.jsxs)("div",{className:"bg-foreground text-background rounded-2xl p-7",children:[(0,n.jsx)("p",{className:"font-serif text-xl font-semibold mb-3 leading-snug",children:"Ready to Start Manufacturing?"}),(0,n.jsx)("p",{className:"text-background/60 text-sm mb-5 leading-relaxed",children:"Get a free quote from our team and launch your brand in weeks."}),(0,n.jsx)(i.N_,{to:"/support/get-a-quote/",children:(0,n.jsxs)(L.Button,{className:"w-full rounded-full bg-primary hover:bg-primary/90 font-medium",children:["Get a Free Quote",(0,n.jsx)(eN.A,{className:"w-4 h-4 ml-1"})]})})]}),(0,n.jsxs)("div",{children:[(0,n.jsx)("p",{className:"text-sm font-semibold text-foreground mb-4",children:"Related Articles"}),(0,n.jsx)("div",{className:"space-y-4",children:d?(0,n.jsx)("p",{className:"text-xs text-muted-foreground",children:"Loading suggestions…"}):0===o.length?(0,n.jsx)(i.N_,{to:"/blog/",className:"text-sm text-primary font-medium hover:underline",children:"Browse all posts"}):o.map(e=>{let t=e.cover_image_url?eB(e.cover_image_url):"https://images.unsplash.com/photo-1558769132-cb1aea458c5e?w=600&q=80",r=e.published_at?(0,to.GP)(new Date(e.published_at),"MMMM d, yyyy"):"";return(0,n.jsxs)(i.N_,{to:"/".concat(e.slug,"/"),className:"group flex gap-3 items-start",children:[(0,n.jsx)("img",{src:t,alt:e.title||"",className:"w-16 h-16 rounded-xl object-cover shrink-0 group-hover:opacity-80 transition-opacity"}),(0,n.jsxs)("div",{children:[(0,n.jsx)("p",{className:"text-xs text-primary mb-1",children:e.category||"Blog"}),(0,n.jsx)("p",{className:"text-sm font-medium text-foreground leading-snug group-hover:text-primary transition-colors line-clamp-2",children:e.title}),r?(0,n.jsx)("p",{className:"text-xs text-muted-foreground mt-1",children:r}):null]})]},e.slug)})})]})]})]})})]})},{})})}),(0,n.jsxs)(s.qh,{path:"/admin",element:(0,n.jsx)(O,{children:(0,n.jsx)(function(){let{pathname:e}=(0,s.zy)(),{logout:t,user:r,role:l}=I(),o=function(e){var t;if(!e)return"Admin";let r=null!=(t=e.user_metadata)?t:{};return r.full_name||r.name||r.preferred_username||(e.email?e.email.split("@")[0]:null)||"Admin"}(r),d=function(e){var t;if(!e)return null;let r=null!=(t=e.user_metadata)?t:{};return r.avatar_url||r.picture||null}(r),[c,u]=(0,a.useState)(()=>e.startsWith("/admin/blog")),[m,h]=(0,a.useState)(()=>e.startsWith("/admin/products")),[p,g]=(0,a.useState)(()=>e.startsWith("/admin/settings")||e.startsWith("/admin/api-settings")),[x,f]=(0,a.useState)(()=>e.startsWith("/admin/seo")||e.startsWith("/admin/auto-linking"));(0,a.useEffect)(()=>{e.startsWith("/admin/blog")&&u(!0)},[e]),(0,a.useEffect)(()=>{e.startsWith("/admin/products")&&h(!0)},[e]),(0,a.useEffect)(()=>{(e.startsWith("/admin/settings")||e.startsWith("/admin/api-settings"))&&g(!0)},[e]),(0,a.useEffect)(()=>{(e.startsWith("/admin/seo")||e.startsWith("/admin/auto-linking"))&&f(!0)},[e]);let v=t=>{let r="/admin/"===t.path?"/admin"===e||"/admin/"===e:e===t.path||e.startsWith("".concat(t.path)),a=t.icon;return(0,n.jsxs)(i.N_,{to:t.path,className:["flex items-center gap-3 px-3 py-2 rounded-lg text-sm font-medium transition-colors",r?"bg-primary text-primary-foreground":"hover:bg-muted text-foreground"].join(" "),children:[(0,n.jsx)(a,{className:"w-4 h-4"}),t.label]},t.path)};return(0,n.jsxs)("div",{className:"flex h-screen min-h-0 overflow-hidden bg-muted/20",children:[(0,n.jsxs)("aside",{className:"flex h-full w-72 shrink-0 flex-col border-r bg-background p-4",children:[(0,n.jsxs)("div",{className:"shrink-0 flex items-center gap-2.5 border-b border-border px-2 pb-3 pt-0",children:[(0,n.jsx)(i.N_,{to:"/",className:"block leading-none",children:(0,n.jsx)("img",{src:"/assets/images/Appar Global Logo_Black.webp",alt:"ApparGlobal",className:"block h-8 w-auto max-w-full"})}),(0,n.jsx)("span",{className:"inline-flex items-center rounded-md bg-primary/10 px-2 py-0.5 text-[10px] font-semibold uppercase tracking-widest text-primary ring-1 ring-inset ring-primary/20",children:"CMS"})]}),(0,n.jsxs)("nav",{className:"mt-4 flex min-h-0 flex-1 flex-col space-y-1 overflow-y-auto",children:[eg.map(v),v({label:"Pages",icon:B.A,path:"/admin/pages/"}),(0,n.jsxs)(Q,{open:m,onOpenChange:h,children:[(0,n.jsxs)(Y,{className:(0,b.cn)("flex w-full items-center justify-between gap-3 px-3 py-2 rounded-lg text-sm font-medium transition-colors",e.startsWith("/admin/products")?"bg-primary text-primary-foreground":"hover:bg-muted text-foreground"),children:[(0,n.jsxs)("span",{className:"flex items-center gap-3",children:[(0,n.jsx)(F.A,{className:"w-4 h-4"}),"Products"]}),(0,n.jsx)(U.A,{className:(0,b.cn)("w-4 h-4 shrink-0 transition-transform",m&&"rotate-180")}
1)]}),(0,n.jsx)(J,{className:"space-y-0.5 pt-1 pl-2",children:eb.map(t=>{let r=function(e){let t=(e||"").replace(/\/+$/,"")||"/";if("/admin/products"===t)return"list";if(!t.startsWith("/admin/products/"))return null;let r=t.slice(16);if(!r)return"list";let n=r.split("/")[0];return"edit"===n?"list":n}(e)===t.key;return(0,n.jsx)(i.N_,{to:t.path,className:(0,b.cn)("block rounded-lg py-2 pl-9 pr-3 text-sm transition-colors",r?"bg-primary/15 text-primary font-medium":"text-muted-foreground hover:text-foreground hover:bg-muted/60"),children:t.label},t.path)})})]}),(0,n.jsxs)(Q,{open:c,onOpenChange:u,children:[(0,n.jsxs)(Y,{className:(0,b.cn)("flex w-full items-center justify-between gap-3 px-3 py-2 rounded-lg text-sm font-medium transition-colors",e.startsWith("/admin/blog")?"bg-primary text-primary-foreground":"hover:bg-muted text-foreground"),children:[(0,n.jsxs)("span",{className:"flex items-center gap-3",children:[(0,n.jsx)(z.A,{className:"w-4 h-4"}),"Blog"]}),(0,n.jsx)(U.A,{className:(0,b.cn)("w-4 h-4 shrink-0 transition-transform",c&&"rotate-180")})]}),(0,n.jsx)(J,{className:"space-y-0.5 pt-1 pl-2",children:ev.map(t=>{let r="/admin/blog/categories/"===t.path?"/admin/blog/categories"===e||"/admin/blog/categories/"===e:"/admin/blog/new/"===t.path?"/admin/blog/new"===e||"/admin/blog/new/"===e:"/admin/blog"===e||"/admin/blog/"===e||e.startsWith("/admin/blog/")&&"/admin/blog/new"!==e&&"/admin/blog/new/"!==e&&"/admin/blog/categories"!==e&&"/admin/blog/categories/"!==e;return(0,n.jsx)(i.N_,{to:t.path,state:"/admin/blog/new/"===t.path?{blankNewPost:!0}:void 0,className:(0,b.cn)("block rounded-lg py-2 pl-9 pr-3 text-sm transition-colors",r?"bg-primary/15 text-primary font-medium":"text-muted-foreground hover:text-foreground hover:bg-muted/60"),children:t.label},t.path)})})]}),v({label:"Media",icon:K.A,path:"/admin/media/"}),(0,n.jsxs)(Q,{open:x,onOpenChange:f,children:[(0,n.jsxs)(Y,{className:(0,b.cn)("flex w-full items-center justify-between gap-3 px-3 py-2 rounded-lg text-sm font-medium transition-colors",e.startsWith("/admin/seo")||e.startsWith("/admin/auto-linking")?"bg-primary text-primary-foreground":"hover:bg-muted text-foreground"),children:[(0,n.jsxs)("span",{className:"flex items-center gap-3",children:[(0,n.jsx)(G.A,{className:"w-4 h-4"}),"Appar SEO"]}),(0,n.jsx)(U.A,{className:(0,b.cn)("w-4 h-4 shrink-0 transition-transform",x&&"rotate-180")})]}),(0,n.jsx)(J,{className:"space-y-0.5 pt-1 pl-2",children:ex.map(t=>{let r="/admin/seo/overview/"===t.path?"/admin/seo/overview"===e||"/admin/seo/overview/"===e:e===t.path||e===t.path.replace(/\/$/,"");return(0,n.jsx)(i.N_,{to:t.path,className:(0,b.cn)("block rounded-lg py-2 pl-9 pr-3 text-sm transition-colors",r?"bg-primary/15 text-primary font-medium":"text-muted-foreground hover:text-foreground hover:bg-muted/60"),children:t.label},t.path)})})]}),ef.map(v),(0,n.jsxs)(Q,{open:p,onOpenChange:g,children:[(0,n.jsxs)(Y,{className:(0,b.cn)("flex w-full items-center justify-between gap-3 px-3 py-2 rounded-lg text-sm font-medium transition-colors",e.startsWith("/admin/settings")||e.startsWith("/admin/api-settings")?"bg-primary text-primary-foreground":"hover:bg-muted text-foreground"),children:[(0,n.jsxs)("span",{className:"flex items-center gap-3",children:[(0,n.jsx)(W.A,{className:"w-4 h-4"}),"Settings"]}),(0,n.jsx)(U.A,{className:(0,b.cn)("w-4 h-4 shrink-0 transition-transform",p&&"rotate-180")})]}),(0,n.jsx)(J,{className:"space-y-0.5 pt-1 pl-2",children:ey.map(t=>{let r=function(e){let t=(e||"").replace(/\/+$/,"")||"/";return t.startsWith("/admin/api-settings")?"api-settings":t.startsWith("/admin/settings")?"/admin/settings"===t?"general":t.slice(16).split("/")[0]||"general":null}(e)===t.key;return(0,n.jsx)(i.N_,{to:t.path,className:(0,b.cn)("block rounded-lg py-2 pl-9 pr-3 text-sm transition-colors",r?"bg-primary/15 text-primary font-medium":"text-muted-foreground hover:text-foreground hover:bg-muted/60"),children:t.label},t.path)})})]})]}),(0,n.jsx)("div",{className:"mt-4 shrink-0 border-t border-border/80 pt-4",children:(0,n.jsxs)("div",{className:(0,b.cn)("flex w-full items-center gap-2 rounded-xl border border-border/80 bg-card px-2.5 py-2.5 shadow-sm","sm:gap-3 sm:px-3"),children:[(0,n.jsxs)(X,{className:"h-10 w-10 shrink-0 border border-border/60",children:[d?(0,n.jsx)(Z,{src:d,alt:""}):null,(0,n.jsx)(ee,{className:"text-xs font-semibold",children:function(e){let t=String(e||"").trim();if(!t)return"A";
1let r=t.split(/\s+/).filter(Boolean);return r.length>=2?"".concat(r[0][0]).concat(r[r.length-1][0]).toUpperCase():t.slice(0,2).toUpperCase()}(o)})]}),(0,n.jsxs)("div",{className:"min-w-0 flex-1",children:[(0,n.jsx)("p",{className:"truncate text-sm font-semibold text-foreground",children:o}),l?(0,n.jsx)("p",{className:"truncate text-xs capitalize text-muted-foreground",children:l}):null]}),(0,n.jsxs)(L.Button,{type:"button",variant:"outline",size:"sm",className:"shrink-0 gap-1.5 px-2.5 h-9 font-medium",onClick:()=>void t(),"aria-label":"Log out",children:[(0,n.jsx)(H.A,{className:"h-3.5 w-3.5","aria-hidden":!0}),"Logout"]})]})})]}),(0,n.jsx)("main",{className:"flex min-h-0 min-w-0 flex-1 flex-col overflow-hidden",children:(0,n.jsx)("div",{className:"min-h-0 flex-1 overflow-y-auto px-6 pb-6 pt-0",children:(0,n.jsx)("div",{className:"min-h-0 pt-4",children:(0,n.jsx)(eh,{children:(0,n.jsx)(a.Suspense,{fallback:(0,n.jsx)("div",{className:"flex items-center justify-center py-16",children:(0,n.jsx)("div",{className:"h-8 w-8 animate-spin rounded-full border-4 border-slate-200 border-t-slate-800"})}),children:(0,n.jsx)(s.sv,{})})})})})})]})},{})}),children:[(0,n.jsx)(s.qh,{index:!0,element:(0,n.jsx)(function(){var e;let{data:t,isLoading:r,error:s}=(0,eK.I)({queryKey:["admin","counts"],queryFn:tL}),{data:l,isLoading:o}=(0,eK.I)({queryKey:["admin","blog_posts"],queryFn:tI,staleTime:6e4}),d=(0,a.useMemo)(()=>(null==l?void 0:l.posts)?function(e){let t=e.filter(e=>!e.deleted_at),r=tq(t),n=0;for(let e of t){let t=tM(tE(e));t&&(r.get(t)||0)>1&&(n+=1)}let a=0,s=0;for(let e of t)String(e.seo_title||"").trim()||String(e.title||"").trim()||(a+=1),tT(e)||(s+=1);return{totalActive:t.length,missingMetaTitle:a,missingMetaDescription:s,duplicateTitlePosts:n}}(l.posts):null,[l]);return(0,n.jsxs)("div",{className:"space-y-6",children:[(0,n.jsxs)("div",{children:[(0,n.jsx)("h1",{className:"text-2xl font-semibold",children:"Dashboard"}),(0,n.jsx)("p",{className:"text-sm text-muted-foreground",children:"Manage your CMS content and SEO."})]}),s?(0,n.jsx)("div",{className:"rounded-lg border border-destructive/30 bg-destructive/10 px-3 py-2 text-sm text-destructive",children:s.message}):null,(0,n.jsxs)("div",{className:"grid sm:grid-cols-2 gap-4",children:[(0,n.jsxs)("div",{className:"rounded-2xl border bg-card p-5",children:[(0,n.jsx)("p",{className:"text-sm text-muted-foreground",children:"Blog posts"}),(0,n.jsx)("p",{className:"mt-2 text-3xl font-semibold",children:r?"—":null==t?void 0:t.posts})]}),(0,n.jsxs)("div",{className:"rounded-2xl border bg-card p-5",children:[(0,n.jsx)("p",{className:"text-sm text-muted-foreground",children:"Pages with SEO overrides"}),(0,n.jsx)("p",{className:"mt-2 text-3xl font-semibold",children:r?"—":null==t?void 0:t.pages})]})]}),(0,n.jsxs)("div",{children:[(0,n.jsx)("h2",{className:"text-sm font-medium text-muted-foreground",children:"SEO snapshot (live posts, not trash)"}),(0,n.jsxs)("p",{className:"mt-1 text-xs text-muted-foreground",children:["Based on titles, meta fields, and duplicates. Image alt and H1 are checked on the"," ",(0,n.jsx)(i.N_,{to:"/admin/blog/",className:"font-medium text-primary underline-offset-2 hover:underline",children:"Blog"})," ","list per page."]}),(0,n.jsxs)("div",{className:"mt-3 grid gap-4 sm:grid-cols-3",children:[(0,n.jsxs)("div",{className:"rounded-2xl border bg-card p-5",children:[(0,n.jsx)("p",{className:"text-sm text-muted-foreground",children:"Missing meta description"}),(0,n.jsx)("p",{className:"mt-2 text-3xl font-semibold",children:o||!d?"—":d.missingMetaDescription}),(0,n.jsxs)("p",{className:"mt-1 text-xs text-muted-foreground",children:["of ",o?"…":null!=(e=null==d?void 0:d.totalActive)?e:"—"," posts"]})]}),(0,n.jsxs)("div",{className:"rounded-2xl border bg-card p-5",children:[(0,n.jsx)("p",{className:"text-sm text-muted-foreground",children:"Duplicate SEO titles"}),(0,n.jsx)("p",{className:"mt-2 text-3xl font-semibold",children:o||!d?"—":d.duplicateTitlePosts}),(0,n.jsx)("p",{className:"mt-1 text-xs text-muted-foreground",children:"posts sharing an effective title"})]}),(0,n.jsxs)("div",{className:"rounded-2xl border bg-card p-5",children:[(0,n.jsx)("p",{className:"text-sm text-muted-foreground",children:"Missing title entirely"}),(0,n.jsx)("p",{className:"mt-2 text-3xl font-semibold",children:o||!d?"—":d.missingMetaTitle}),(0,n.jsx)("p",{className:"mt-1 text-xs text-muted-foreground",children:"no post title and no SEO title"})]})]})]})]})},{})}),(0,n.jsx)(s.qh,{path:"users",element:(0,n.jsx)(function(){let{user:e}=I(),t=(0,o.jE)(),[r,s]=(0,a.useState)(""),{data:i,isLoading:l,error:d}=(0,eK.I)({queryKey:["admin","users"],queryFn:tK}),c=(0,tO.n)({mutationFn:async e=>{let{userId:t,currentRole:r}=e,n="admin"===r?"user":"admin",{data:a}=await T.N.from("user_roles").select("id").eq("id",t).maybeSingle();if(a){let{error:e}=await T.N.from("user_roles").update({role:n}).eq("id",t);if(e)throw e}else{let{error:e}=await T.N.from("user_roles").insert({id:t,role:n});if(e)throw e}return{userId:t,newRole:n}},onSuccess:e=>{let{newRole:r}=e;t.invalidateQueries({queryKey:["admin","users"]}),f({title:"Role updated",description:"User role changed to ".concat(r,".")})},onError:e=>{f({variant:"destructive",title:"Error updating role",description:e.message})}}),u=a.useMemo(()=>
1{if(!i)return[];if(!r.trim())return i;let e=r.toLowerCase();return i.filter(t=>{let r=(t.email||"").toLowerCase(),n=("string"==typeof t.display_name?t.display_name:"").toLowerCase();return r.includes(e)||n.includes(e)})},[i,r]);return(0,n.jsxs)("div",{className:"space-y-6",children:[(0,n.jsx)("div",{className:"flex items-start justify-between gap-4",children:(0,n.jsxs)("div",{children:[(0,n.jsx)("h1",{className:"text-2xl font-semibold",children:"Users"}),(0,n.jsx)("p",{className:"text-sm text-muted-foreground",children:"Manage user roles and permissions."})]})}),(0,n.jsx)("div",{className:"flex items-center gap-3",children:(0,n.jsxs)("div",{className:"relative flex-1 max-w-md",children:[(0,n.jsx)(tF.A,{className:"absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-muted-foreground"}),(0,n.jsx)(tR.p,{value:r,onChange:e=>s(e.target.value),placeholder:"Search by display name or email...",className:"pl-9"})]})}),d?(0,n.jsxs)("div",{className:"rounded-lg border border-destructive/30 bg-destructive/10 px-3 py-2 text-sm text-destructive",children:[d.message,(0,n.jsx)("p",{className:"mt-2 text-xs opacity-80",children:"Note: You may need to run the `scripts/ensure-user-roles.sql` script in your Supabase SQL editor to create the necessary RPC."})]}):null,(0,n.jsxs)("div",{className:"rounded-2xl border bg-card overflow-hidden",children:[(0,n.jsxs)("div",{className:"grid grid-cols-[2fr_1fr_1fr_140px] gap-4 border-b px-4 py-3 text-xs font-medium text-muted-foreground",children:[(0,n.jsx)("div",{children:"User"}),(0,n.jsx)("div",{children:"Role"}),(0,n.jsx)("div",{children:"Joined"}),(0,n.jsx)("div",{className:"text-right",children:"Actions"})]}),l?(0,n.jsx)("div",{className:"px-4 py-6 text-sm text-muted-foreground",children:"Loading users..."}):0===u.length?(0,n.jsx)("div",{className:"px-4 py-6 text-sm text-muted-foreground",children:"No users found."}):(0,n.jsx)("div",{className:"divide-y",children:u.map(t=>{let r="admin"===t.role,a=t.id===(null==e?void 0:e.id);return(0,n.jsxs)("div",{className:"grid grid-cols-[2fr_1fr_1fr_140px] items-center gap-4 px-4 py-3",children:[(0,n.jsxs)("div",{className:"min-w-0",children:[(0,n.jsx)("p",{className:"font-medium truncate",children:function(e){let t="string"==typeof e.display_name?e.display_name.trim():"";if(t)return t;let r=e.email||"",n=r.indexOf("@");return n>0?r.slice(0,n):r||"—"}(t)}),(0,n.jsx)("p",{className:"text-xs text-muted-foreground truncate mt-0.5",children:t.email||"—"})]}),(0,n.jsx)("div",{children:(0,n.jsxs)(tB,{variant:r?"default":"secondary",className:"gap-1",children:[r?(0,n.jsx)(tU.A,{className:"w-3 h-3"}):(0,n.jsx)(tz.A,{className:"w-3 h-3"}),r?"Admin":"User"]})}),(0,n.jsx)("div",{className:"text-sm text-muted-foreground",children:new Date(t.created_at).toLocaleDateString()}),(0,n.jsx)("div",{className:"text-right",children:(0,n.jsx)(L.Button,{size:"sm",variant:r?"destructive":"default",onClick:()=>c.mutate({userId:t.id,currentRole:t.role}),disabled:a||c.isPending,className:"w-full",children:r?"Remove Admin":"Make Admin"})})]},t.id)})})]})]})},{})}),(0,n.jsx)(s.qh,{path:"blog/categories",element:(0,n.jsx)(function(){let e=(0,o.jE)(),{data:t,isLoading:r,error:s}=(0,eK.I)({queryKey:["admin","blog_categories","rows"],queryFn:t5}),[l,d]=(0,a.useState)(""),[c,u]=(0,a.useState)(0),[m,h]=(0,a.useState)(null),p=(0,tO.n)({mutationFn:async e=>{let{data:t,error:r}=await T.N.from("blog_categories").insert(e).select("*").single();if(r)throw r;return t},onSuccess:()=>{e.invalidateQueries({queryKey:["admin","blog_categories","rows"]}),e.invalidateQueries({queryKey:["admin","blog_categories","names"]}),d(""),u(0)}}),g=(0,tO.n)({mutationFn:async e=>{let{id:t,oldName:r,name:n,slug:a,sort_order:s}=e,{data:i,error:l}=await T.N.from("blog_categories").update({name:n,slug:a,sort_order:s}).eq("id",t).select("*").single();if(l)throw l;if(n&&n!==r){let{error:e}=await T.N.from("blog_posts").update({category:n}).eq("category",r);if(e)throw e}return i},onSuccess:()=>{e.invalidateQueries({queryKey:["admin","blog_categories","rows"]}),e.invalidateQueries({queryKey:["admin","blog_categories","names"]}
1),e.invalidateQueries({queryKey:["admin","blog_posts"]}),h(null)}}),x=(0,tO.n)({mutationFn:async e=>{if(await t3(e.name)>0){let{error:t}=await T.N.from("blog_posts").update({category:null}).eq("category",e.name);if(t)throw t}let{error:t}=await T.N.from("blog_categories").delete().eq("id",e.id);if(t)throw t},onSuccess:()=>{e.invalidateQueries({queryKey:["admin","blog_categories","rows"]}),e.invalidateQueries({queryKey:["admin","blog_categories","names"]}),e.invalidateQueries({queryKey:["admin","blog_posts"]})}}),f=(0,tO.n)({mutationFn:async()=>{let{data:e,error:t}=await T.N.from("blog_posts").select("category");if(t)throw t;let r=[...new Set((e||[]).map(e=>String(e.category||"").trim()).filter(Boolean))],{data:n}=await T.N.from("blog_categories").select("sort_order"),a=0;for(let e of((null==n?void 0:n.length)&&(a=Math.max(...n.map(e=>{var t;return null!=(t=e.sort_order)?t:0}),0)),r)){let{data:t}=await T.N.from("blog_categories").select("id").eq("name",e).maybeSingle();if(t)continue;a+=1;let r=t4(e)||"category-".concat(a),{error:n}=await T.N.from("blog_categories").insert({name:e,slug:r,sort_order:a});if(n)throw n}},onSuccess:()=>{e.invalidateQueries({queryKey:["admin","blog_categories","rows"]}),e.invalidateQueries({queryKey:["admin","blog_categories","names"]})}}),v=(0,a.useMemo)(()=>t||[],[t]);return(0,n.jsxs)("div",{className:"space-y-6",children:[(0,n.jsxs)("div",{className:"flex items-start justify-between gap-4",children:[(0,n.jsxs)("div",{children:[(0,n.jsxs)("p",{className:"text-sm text-muted-foreground mb-1",children:[(0,n.jsx)(i.N_,{to:"/admin/blog/",className:"hover:underline",children:"Blog"})," ","/ Categories"]}),(0,n.jsx)("h1",{className:"text-2xl font-semibold",children:"Categories"}),(0,n.jsx)("p",{className:"text-sm text-muted-foreground mt-1",children:"Manage blog post categories. Post editor suggests these names."})]}),(0,n.jsx)("div",{className:"flex gap-2",children:(0,n.jsx)(L.Button,{type:"button",variant:"outline",onClick:()=>f.mutate(),disabled:f.isPending,children:f.isPending?"Syncing…":"Sync from existing posts"})})]}),s?(0,n.jsxs)("div",{className:"rounded-lg border border-destructive/30 bg-destructive/10 px-3 py-2 text-sm text-destructive space-y-2",children:[(0,n.jsx)("p",{children:s.message}),(0,n.jsxs)("p",{className:"text-xs opacity-90",children:["If the table is missing, run ",(0,n.jsx)("code",{className:"rounded bg-background px-1",children:"scripts/ensure-blog-categories.sql"})," in Supabase SQL Editor."]})]}):null,(0,n.jsxs)("div",{className:"rounded-2xl border bg-card p-5 space-y-4",children:[(0,n.jsx)("p",{className:"text-sm font-medium",children:"Add category"}),(0,n.jsxs)("div",{className:"grid md:grid-cols-[1fr_120px_auto] gap-3 items-end",children:[(0,n.jsxs)("div",{className:"grid gap-2",children:[(0,n.jsx)(tH,{htmlFor:"new-name",children:"Name"}),(0,n.jsx)(tR.p,{id:"new-name",value:l,onChange:e=>d(e.target.value),placeholder:"e.g. Sustainability"})]}),(0,n.jsxs)("div",{className:"grid gap-2",children:[(0,n.jsx)(tH,{htmlFor:"new-sort",children:"Sort"}),(0,n.jsx)(tR.p,{id:"new-sort",type:"number",value:c,onChange:e=>u(Number(e.target.value)||0)})]}),(0,n.jsx)(L.Button,{type:"button",onClick:()=>{let e=l.trim();e&&p.mutate({name:e,slug:t4(e),sort_order:c})},disabled:p.isPending||!l.trim(),children:"Add"})]})]}),(0,n.jsxs)("div",{className:"rounded-2xl border bg-card overflow-hidden",children:[(0,n.jsxs)("div",{className:"grid grid-cols-[1fr_120px_100px_140px] gap-0 border-b px-4 py-3 text-xs font-medium text-muted-foreground",children:[(0,n.jsx)("div",{children:"Name"}),(0,n.jsx)("div",{children:"Slug"}),(0,n.jsx)("div",{children:"Sort"}),(0,n.jsx)("div",{className:"text-right",children:"Actions"})]}),r?(0,n.jsx)("div",{className:"px-4 py-6 text-sm text-muted-foreground",children:"Loading…"}):0===v.length?(0,n.jsx)("div",{className:"px-4 py-6 text-sm text-muted-foreground",children:"No categories yet. Add one or sync from posts."}):(0,n.jsx)("div",{className:"divide-y",children:v.map(e=>(0,n.jsxs)("div",{className:"grid grid-cols-[1fr_120px_100px_140px] items-center px-4 py-3",children:[(0,n.jsx)("div",{className:"text-sm font-medium truncate",children:e.name}),(0,n.jsx)("div",{className:"text-xs text-muted-foreground truncate",children:e.slug}),(0,n.jsx)("div",{className:"text-sm text-muted-foreground",children:e.sort_order}),(0,n.jsxs)("div",{className:"text-right flex justify-end gap-2",children:[(0,n.jsx)(L.Button,{type:"button",size:"sm",variant:"outline",onClick:()=>h(e),children:"Edit"}),(0,n.jsx)(L.Button,{type:"button",size:"sm",variant:"destructive",onClick:()=>{window.confirm("Delete “".concat(e.name,"”? Posts using it will have category cleared."))&&x.mutate(e)},disabled:x.isPending,children:"Delete"})]})]},e.id))})]}),(0,n.jsx)(tQ,{open:!!m,onOpenChange:e=>!e&&h(null),children:(0,n.jsxs)(tX,{children:[(0,n.jsxs)(tZ,{children:[(0,n.jsx)(t1,{children:"Edit c
1ategory"}),(0,n.jsx)(t2,{children:"Renaming updates all posts that used the old name."})]}),m?(0,n.jsx)(t6,{row:m,onCancel:()=>h(null),onSave:e=>g.mutateAsync({id:m.id,oldName:m.name,name:e.name,slug:e.slug,sort_order:e.sort_order}).then(()=>h(null)),isSaving:g.isPending}):null]})})]})},{})}),(0,n.jsx)(s.qh,{path:"blog",element:(0,n.jsx)(function(){var e,t,r,s;let{user:l}=I(),[d,c]=(0,a.useState)(""),[u,m]=(0,a.useState)(""),[h,p]=(0,a.useState)("all"),[g,x]=(0,a.useState)("all"),[v,y]=(0,a.useState)("all"),[j,w]=(0,a.useState)("all"),[_,N]=(0,a.useState)("all"),[k,S]=(0,a.useState)(1),[C,A]=(0,a.useState)(null),[E,q]=(0,a.useState)(()=>new Set),[M,P]=(0,a.useState)("none"),[O,R]=(0,a.useState)(!1),[D,B]=(0,a.useState)(rw),[F,U]=(0,a.useState)("unchanged"),[z,K]=(0,a.useState)(rw),[G,W]=(0,a.useState)(!1),[H,V]=(0,a.useState)(!1),[Q,Y]=(0,a.useState)(null),[J,$]=(0,a.useState)(!1),X=(0,o.jE)(),{data:Z,isLoading:ee,error:et}=(0,eK.I)({queryKey:["admin","blog_posts"],queryFn:tI,refetchInterval:12e3}),{data:en=[]}=(0,eK.I)({queryKey:["admin","blog_categories","names"],queryFn:rN,staleTime:6e4}),ea=null!=(e=null==Z?void 0:Z.posts)?e:[],em=null!=(t=null==Z?void 0:Z.authorById)?t:{},eh=null!=(r=null==Z?void 0:Z.usersForAuthor)?r:[],ep=null!=(s=null==Z?void 0:Z.editSessionsByPostId)?s:{},eg=(0,a.useMemo)(()=>ea.filter(e=>!e.deleted_at),[ea]),ex=(0,a.useMemo)(()=>ea.filter(e=>e.deleted_at),[ea]),ef="trash"===_?ex:eg,ev=ex.length,ey=(0,a.useMemo)(()=>{let e=new Set(en);for(let t of ef){let r=String(t.category||"").trim();r&&e.add(r)}return Array.from(e).sort((e,t)=>e.localeCompare(t))},[en,ef]),eb=(0,a.useMemo)(()=>{let e=new Set;for(let t of ef){let r=rk(rS(t));r&&e.add(r)}return Array.from(e).sort().reverse()},[ef]),ej=(0,a.useMemo)(()=>{let e=0,t=0,r=0;for(let n of eg){let{isPublished:a,isScheduled:s}=rM(n);a?e+=1:s?t+=1:r+=1}return{all:eg.length,published:e,scheduled:t,draft:r}},[eg]),ew=(0,a.useMemo)(()=>tq(eg),[eg]),e_=(0,a.useMemo)(()=>{let e=u.trim().toLowerCase(),t=ef.filter(e=>{if("trash"===_)return!0;let{isPublished:t,isScheduled:r}=rM(e);return("draft"!==_||!t&&!r)&&("published"!==_||!!t)&&("scheduled"!==_||!!r)});return("all"!==g&&(t=t.filter(e=>String(e.category||"").trim()===g)),"all"!==j&&(t=t.filter(e=>rk(rS(e))===j)),e)?t.filter(t=>{let r=rA(t,em).toLowerCase();return String(t.title||"").toLowerCase().includes(e)||String(t.slug||"").toLowerCase().includes(e)||String(t.category||"").toLowerCase().includes(e)||r.includes(e)}):t},[ef,u,_,g,j,em]),eN=(0,a.useMemo)(()=>e_.map(e=>e.id).join(","),[e_]);(0,a.useEffect)(()=>{q(e=>{let t=new Set(e_.map(e=>e.id)),r=new Set;return e.forEach(e=>{t.has(e)&&r.add(e)}),r})},[eN]);let ek=e_.length,eS=Math.max(1,Math.ceil(ek/20));(0,a.useEffect)(()=>{S(1)},[u,_,g,j]),(0,a.useEffect)(()=>{P("none")},[_]),(0,a.useEffect)(()=>{S(e=>Math.min(Math.max(1,e),eS))},[eS]);let eC=Math.min(Math.max(1,k),eS),eA=(eC-1)*20,eE=e_.slice(eA,eA+20),eT=eE.map(e=>e.id).join(","),{data:eq={},isPending:eM}=(0,eK.I)({queryKey:["admin","blog_posts","bodies",eT],queryFn:async()=>{let e=eE.map(e=>e.id);if(0===e.length)return{};let{data:t,error:r}=await T.N.from("blog_posts").select("id, content").in("id",e);if(r)throw r;return Object.fromEntries((t||[]).map(e=>{var t;return[e.id,null!=(t=e.content)?t:""]}))},enabled:eE.length>0,staleTime:3e4}),eP=0===ek?0:eA+1,eI=Math.min(eA+20,ek),eL=!!u.trim()||"all"!==_||"all"!==g||"all"!==j,eO=d.trim()!==u.trim()||h!==g||v!==j,eR=eL||eO||"trash"===_,eD=eE.map(e=>e.id),eB=(0,a.useMemo)(()=>eE.filter(e=>!rT(e.id,_,ep,null==l?void 0:l.id)).map(e=>e.id),[eE,_,ep,null==l?void 0:l.id]),eF=eB.length>0&&eB.every(e=>E.has(e)),eU=eB.some(e=>E.has(e))&&!eF,ez=(0,a.useCallback)((e,t)=>{q(r=>{let n=new Set(r);return t?n.add(e):n.delete(e),n})},[]),eG=(0,a.useCallback)(e=>{q(t=>{let r=new Set(t);return e?eB.forEach(e=>r.add(e)):eD.forEach(e=>r.delete(e)),r})},[eD,eB]),eW=(0,a.useCallback)(()=>{q(new Set(e_.filter(e=>!rT(e.id,_,ep,null==l?void 0:l.id)).map(e=>e.id)))},[e_,_,ep,null==l?void 0:l.id]);(0,a.useEffect)(()=>{q(e=>{if(0===e.size)return e;let t=new Set(e);for(let r of e)rT(r,_,ep,null==l?void 0:l.id)&&t.delete(r);return t.size===e.size?e:t})},[_,ep,null==l?void 0:l.id]);let eH=(0,a.useCallback)(()=>{X.invalidateQueries({queryKey:["admin","blog_posts"]}),X.invalidateQueries({queryKey:["public","blog_posts"]})},[X]),eV=(0,tO.n)({mutationFn:async e=>{let t=new Date().toISOString(),{error:r}=await T.N.from("blog_posts").update({deleted_at:t,updated_at:t}).eq("id",e);if(r)throw r},onSuccess:()=>{eH(),f({title:"Moved to trash",description:"You can restore it from Trash or delete it permanently there."}),A(null)},onError:e=>{f({title:"Could not move to trash",description:(0,T.z)(e)||"Try again.",variant:"destructive"})}}),eQ=(0,tO.n)({mutationFn:async e=>{let{error:t}=await T.N.from("blog_posts").delete().eq("id",e);if(t)throw t},onSuccess:()=>{eH(),f({title:"Permanently deleted"}),Y(null)},onError:e=>{f({title:"Delete failed",description:(0,T.z)(e)||"Check database foreign keys (409) or RLS.",variant:"destructive"})}}),eY=(0,tO.n)({mutationFn:async e=>{let t=new Date().toISOString(),{error:r}=await T.N.from("blog_posts").update({deleted_at:null,updated_at:t}).eq("id",e);if(r)throw r},onSuccess:()=>{eH(),f({title:"Restored",description:"Post is back in All posts."})},onError:e=>{f({title:"Restore failed",description:(0,T.z)(e)||"Try again.",variant:"destructive"})}}),eJ=(0,tO.n)({mutationFn:async e=>{let t=new Date().toISOString(),{error:r}=await T.N.from("blog_posts").update({deleted_at:t,updated_at:t}).in("id",e);if(r)throw r},onSuccess:(e,t)=>{eH(),f({title:"Moved to trash",description:"".concat(t.length," post(s).")}),W(!1),q(new Set),P("none")},onError:e=>{f({title:"Bulk move failed",description:(0,T.z)(e)||"Try again.",variant:"destructive"})}}),e$=(0,tO.n)({mutationFn:async e=>{let t=new Date().toISOString(),{error:r}=await T.N.from("blog_posts").update({deleted_at:null,updated_at:t}).in("id",e);if(r)throw r},onSuccess:(e,t)=>{eH(),f({title:"Restored",description:"".concat(t.length," post(s).")}),q(new Set),P("none")},onError:e=>{f({title:"Bulk restore failed",description:(0,T.z)(e)||"Try again.",variant:"destructive"})}}),eX=(0,tO.n)({mutationFn:async e=>{let{error:t}=await T.N.from("blog_posts").delete().in("id",e);if(t)throw t},onSuccess:(e,t)=>{eH(),f({title:"Permanently deleted",description:"".concat(t.length," post(s).")}),V(!1),q(new Set),P("none")},onError:e=>{f({title:"Bulk delete failed",description:(0,T.z)(e)||"Check database foreign keys (409) or RLS.",variant:"destructive"})}}),eZ=(0,tO.n)({mutationFn:async e=>{if(!e.length)return;let{error:t}=await T.N.from("blog_posts").delete().in("id",e);if(t)throw t},onSuccess:(e,t)=>
1{eH(),$(!1),f({title:"Trash emptied",description:"".concat(t.length," post(s) permanently removed.")})},onError:e=>{f({title:"Empty trash failed",description:(0,T.z)(e)||"Try again.",variant:"destructive"})}}),e0=(0,tO.n)({mutationFn:async e=>{let{ids:t,patch:r}=e,{error:n}=await T.N.from("blog_posts").update(r).in("id",t);if(n)throw n},onSuccess:(e,t)=>{let{ids:r}=t;eH(),f({title:"Posts updated",description:"".concat(r.length," post(s) updated.")}),R(!1),B(rw),U("unchanged"),K(rw),q(new Set),P("none")},onError:e=>{f({title:"Bulk update failed",description:(0,T.z)(e)||"Try again.",variant:"destructive"})}}),e1=(0,a.useMemo)(()=>Array.from(E),[E]),e2=()=>{m(d)},e4=(0,a.useCallback)(()=>{p("all"),x("all"),y("all"),w("all"),c(""),m(""),N("all"),S(1),f({title:"Filters cleared"})},[]),e5="grid min-w-[1080px] grid-cols-[32px_minmax(0,1.25fr)_minmax(0,0.8fr)_minmax(0,0.85fr)_minmax(0,0.95fr)_88px_minmax(0,5.75rem)_150px] gap-2 items-center px-4 py-3";return(0,n.jsxs)("div",{className:"space-y-6",children:[(0,n.jsxs)("div",{className:"flex items-start justify-between gap-4",children:[(0,n.jsxs)("div",{children:[(0,n.jsx)("h1",{className:"text-2xl font-semibold",children:"Blog"}),(0,n.jsx)("p",{className:"text-sm text-muted-foreground",children:"Create posts, manage drafts, and edit SEO fields. The SEO column flags title, meta, duplicates, H1, and image alt (body loads per page)."})]}),(0,n.jsx)(L.Button,{asChild:!0,children:(0,n.jsx)(i.N_,{to:"/admin/blog/new/",state:{blankNewPost:!0},children:"New post"})})]}),(0,n.jsx)("div",{className:"rounded-xl border bg-muted/30 p-4",children:(0,n.jsxs)("div",{className:"flex flex-col gap-4 lg:flex-row lg:items-end lg:justify-between lg:gap-6",children:[(0,n.jsxs)("div",{className:"order-2 flex flex-col gap-1.5 shrink-0 lg:order-1",children:[(0,n.jsx)("span",{className:"text-xs text-muted-foreground",children:"Status"}),(0,n.jsx)(t9,{value:_,onValueChange:N,className:"w-full lg:w-auto",children:(0,n.jsxs)(t7,{className:"h-auto min-h-9 w-full flex-wrap justify-start gap-1 lg:w-auto",children:[(0,n.jsxs)(re,{value:"all",children:["All (",ej.all,")"]}),(0,n.jsxs)(re,{value:"draft",children:["Drafts (",ej.draft,")"]}),(0,n.jsxs)(re,{value:"scheduled",children:["Scheduled (",ej.scheduled,")"]}),(0,n.jsxs)(re,{value:"published",children:["Published (",ej.published,")"]}),(0,n.jsxs)(re,{value:"trash",children:["Trash (",ev,")"]})]})}),"trash"===_?(0,n.jsx)("p",{className:"text-xs text-muted-foreground max-w-xl",children:"Trashed posts are hidden from the live site. Restore or delete permanently here."}):null]}),(0,n.jsxs)("div",{className:"order-1 flex min-w-0 flex-1 flex-col gap-1.5 lg:order-2 lg:max-w-xl lg:items-start",children:[(0,n.jsx)(tH,{htmlFor:"admin-post-search",className:"text-xs text-muted-foreground",children:"Search"}),(0,n.jsxs)("div",{className:"flex w-full min-w-0 flex-nowrap items-center gap-2",children:[(0,n.jsx)(tR.p,{id:"admin-post-search",value:d,onChange:e=>c(e.target.value),onKeyDown:e=>"Enter"===e.key&&e2(),placeholder:"Title, slug, category, author…",className:"min-w-0 flex-1 sm:min-w-[12rem]"}),(0,n.jsx)(L.Button,{type:"button",variant:"secondary",onClick:e2,className:"shrink-0",children:"Search posts"})]})]})]})}),(0,n.jsx)("div",{className:"rounded-xl border bg-muted/30 p-4",children:(0,n.jsxs)("div",{className:"flex w-full flex-col gap-4 sm:flex-row sm:flex-wrap sm:items-end sm:justify-between sm:gap-x-3 sm:gap-y-3",children:[(0,n.jsxs)("div",{className:"flex min-w-0 flex-wrap items-end gap-x-3 gap-y-3",children:[(0,n.jsxs)("div",{className:"flex flex-col gap-1.5 min-w-[160px]",children:[(0,n.jsx)(tH,{className:"text-xs text-muted-foreground",children:"Category"}),(0,n.jsxs)(rl,{value:h,onValueChange:p,children:[(0,n.jsx)(rd,{children:(0,n.jsx)(ro,{placeholder:"All categories"})}),(0,n.jsxs)(rm,{children:[(0,n.jsx)(rh,{value:"all",children:"All categories"}),ey.map(e=>(0,n.jsx)(rh,{value:e,children:e},e))]})]})]}),(0,n.jsxs)("div",{className:"flex flex-col gap-1.5 min-w-[160px]",children:[(0,n.jsx)(tH,{className:"text-xs text-muted-foreground",children:"Month"}),(0,n.jsxs)(rl,{value:v,onValueChange:y,children:[(0,n.jsx)(rd,{children:(0,n.jsx)(ro,{placeholder:"All dates"})}),(0,n.jsxs)(rm,{children:[(0,n.jsx)(rh,{value:"all",children:"All dates"}),eb.map(e=>(0,n.jsx)(rh,{value:e,children:e},e))]})]})]}),(0,n.jsx)(L.Button,{type:"button",variant:"secondary",onClick:()=>{x(h),w(v)},children:"Filter"}),(0,n.jsx)(L.Button,{type:"button",variant:"ghost",className:"text-muted-foreground",onClick:e4,disabled:!eR,children:"Clear filters"})]}),(0,n.jsxs)("div",{className:"flex w-full flex-wrap items-end justify-end gap-x-3 gap-y-3 border-t border-border pt-4 sm:w-auto 
1sm:border-l sm:border-t-0 sm:pl-4 sm:pt-0",children:[(0,n.jsxs)("div",{className:"flex flex-col gap-1.5 min-w-[200px]",children:[(0,n.jsx)(tH,{className:"text-xs text-muted-foreground",children:"Bulk actions"}),(0,n.jsxs)(rl,{value:M,onValueChange:P,children:[(0,n.jsx)(rd,{className:"w-full min-w-[200px] sm:w-[220px]",children:(0,n.jsx)(ro,{placeholder:"Bulk actions"})}),(0,n.jsxs)(rm,{children:[(0,n.jsx)(rh,{value:"none",children:"Bulk actions"}),"trash"===_?(0,n.jsxs)(n.Fragment,{children:[(0,n.jsx)(rh,{value:"restore",children:"Restore"}),(0,n.jsx)(rh,{value:"deletePermanent",children:"Delete permanently"})]}):(0,n.jsxs)(n.Fragment,{children:[(0,n.jsx)(rh,{value:"edit",children:"Edit"}),(0,n.jsx)(rh,{value:"trash",children:"Move to trash"})]})]})]})]}),(0,n.jsx)(L.Button,{type:"button",variant:"default",onClick:()=>{if(0===e1.length)return void f({title:"No posts selected",description:"Select one or more posts first.",variant:"destructive"});if("none"===M)return void f({title:"Choose an action",description:"trash"===_?"Select Restore or Delete permanently.":"Select Bulk Edit or Move to trash.",variant:"destructive"});if("trash"===_)return"edit"===M?void f({title:"Not available in Trash",description:"Restore posts first, then use Bulk edit.",variant:"destructive"}):"restore"===M?void e$.mutate(e1):void("deletePermanent"===M&&V(!0));if("edit"===M){B(rw),U("unchanged"),K(rw),R(!0);return}"trash"===M&&W(!0)},children:"Apply"}),"trash"===_&&ev>0?(0,n.jsx)(L.Button,{type:"button",variant:"destructive",onClick:()=>$(!0),disabled:eZ.isPending,children:"Empty trash"}):null,ek>eE.length?(0,n.jsxs)(L.Button,{type:"button",variant:"outline",size:"sm",onClick:eW,children:["Select all ",ek," filtered"]}):null]})]})}),O?(0,n.jsxs)("div",{className:"rounded-xl border bg-muted/40 p-4 space-y-4",children:[(0,n.jsx)("div",{className:"font-medium text-sm",children:"Bulk edit"}),(0,n.jsxs)("p",{className:"text-sm text-muted-foreground",children:["Updates apply to ",e1.length," selected post(s)."]}),(0,n.jsxs)("div",{className:"grid gap-4 sm:grid-cols-2 lg:grid-cols-3 max-w-4xl",children:[(0,n.jsxs)("div",{className:"space-y-2",children:[(0,n.jsx)(tH,{children:"Category"}),(0,n.jsxs)(rl,{value:D,onValueChange:B,children:[(0,n.jsx)(rd,{children:(0,n.jsx)(ro,{placeholder:"— No change —"})}),(0,n.jsxs)(rm,{children:[(0,n.jsx)(rh,{value:rw,children:"— No change —"}),ey.map(e=>(0,n.jsx)(rh,{value:e,children:e},e))]})]})]}),(0,n.jsxs)("div",{className:"space-y-2",children:[(0,n.jsx)(tH,{children:"Featured"}),(0,n.jsxs)(rl,{value:F,onValueChange:U,children:[(0,n.jsx)(rd,{children:(0,n.jsx)(ro,{})}),(0,n.jsxs)(rm,{children:[(0,n.jsx)(rh,{value:"unchanged",children:"— No change —"}),(0,n.jsx)(rh,{value:"true",children:"Featured"}),(0,n.jsx)(rh,{value:"false",children:"Not featured"})]})]})]}),(0,n.jsxs)("div",{className:"space-y-2 sm:col-span-2 lg:col-span-1",children:[(0,n.jsx)(tH,{children:"Author"}),(0,n.jsxs)(rl,{value:z,onValueChange:K,children:[(0,n.jsx)(rd,{children:(0,n.jsx)(ro,{placeholder:"— No change —"})}),(0,n.jsxs)(rm,{children:[(0,n.jsx)(rh,{value:rw,children:"— No change —"}),(0,n.jsx)(rh,{value:r_,children:"— Unassigned —"}),eh.map(e=>(0,n.jsx)(rh,{value:e.id,title:e.email||void 0,children:rE(e)},e.id))]})]}),(0,n.jsx)("p",{className:"text-xs text-muted-foreground",children:"Applies to every selected post."})]})]}),(0,n.jsxs)("div",{className:"flex flex-wrap gap-2",children:[(0,n.jsx)(L.Button,{type:"button",onClick:()=>{if(0===e1.length)return;let e=D!==rw,t="unchanged"!==F,r=z!==rw;if(!e&&!t&&!r)return void f({title:"Nothing to change",description:"Pick category, featured, or author.",variant:"destructive"});let n={updated_at:new Date().toISOString()};e&&(n.category=D.trim()||null),t&&(n.featured="true"===F),r&&(n.created_by=z===r_?null:z),e0.mutate({ids:e1,patch:n})},disabled:e0.isPending,children:e0.isPending?"Updating…":"Update"}),(0,n.jsx)(L.Button,{type:"button",variant:"outline",onClick:()=>R(!1),children:"Cancel"})]})]}):null,et?(0,n.jsx)("div",{className:"rounded-lg border border-destructive/30 bg-destructive/10 px-3 py-2 text-sm text-destructive",children:et.message}):null,(0,n.jsxs)("div",{className:"rounded-2xl border bg-card overflow-hidden",children:[(0,n.jsxs)("div",{className:(0,b.cn)(e5,"border-b text-xs font-medium text-muted-foreground"),children:[(0,n.jsx)("div",{className:"flex justify-center",children:(0,n.jsx)(ra,{checked:!!eF||!!eU&&"indeterminate",onCheckedChange:e=>eG(!0===e),"aria-label":"Select all posts on this page"})}),(0,n.jsx)("div",{children:"Title"}),(0,n.jsx)("div",{children:"Category"}),(0,n.jsx)("div",{children:"Author"}),(0,n.jsx)("div",{children:"Date"}),(0,n.jsx)("div",{children:"Status"}),(0,n.jsx)("div",{className:"text-center",children:"SEO"}),(0,n.jsx)("div",{className:"text-right",children:"Actions"})]}),ee?(0,n.jsx)("div",{className:"px-4 py-6 text-sm text-muted-foreground",children:"Loading…"}):0===e_.length?(0,n.jsx)("div",{className:"px-4 py-6 text-sm text-muted-foreground",children:"No posts found."}):(0,n.jsx)("div",{className:"divide-y overflow-x-auto",children:eE.map(e=>{let{isPublished:t,isScheduled:r}=rM(e),{label:a,line2:s}=function(e){let{isPublished:t,isScheduled:r}=rM(e),n=t||r?e.published_at:e.updated_at||e.created_at;return{label:t?"Published":r?"Scheduled":"Last modified",line2:n?new Date(n).toLocaleStr
1ing(void 0,{dateStyle:"medium",timeStyle:"short"}):"—"}}(e),o=ep[e.id],d=null==o?void 0:o.userId,c=!!d,u=!!((null==l?void 0:l.id)&&d===l.id),m=d?function(e,t){let r=(t||[]).find(t=>t.id===e);return r?rE(r):"Someone"}(d,eh):null,h=rT(e.id,_,ep,null==l?void 0:l.id),p="Another admin is editing this post. Try again when they finish.";return(0,n.jsxs)("div",{className:(0,b.cn)(e5,"py-3"),children:[(0,n.jsx)("div",{className:"flex justify-center",children:(0,n.jsx)(ra,{checked:E.has(e.id),onCheckedChange:t=>ez(e.id,!0===t),disabled:h,"aria-label":"Select ".concat(e.title||"post")})}),(0,n.jsxs)("div",{className:"min-w-0",children:[(0,n.jsxs)("div",{className:"flex flex-wrap items-start gap-2 min-w-0",children:[(0,n.jsx)("p",{className:"font-medium min-w-0 flex-1 break-words text-pretty",children:e.title||"(untitled)"}),e.featured?(0,n.jsx)(tB,{variant:"secondary",className:"shrink-0",children:"Featured"}):null]}),c?(0,n.jsxs)("div",{className:"mt-1 flex items-center gap-1.5 text-xs text-muted-foreground",children:[(0,n.jsx)(rx.A,{className:"h-3.5 w-3.5 shrink-0 opacity-70","aria-hidden":!0}),(0,n.jsx)("span",{children:u?(0,n.jsxs)(n.Fragment,{children:[(0,n.jsx)("span",{className:"font-medium text-foreground",children:"You"})," are editing this post"]}):(0,n.jsxs)(n.Fragment,{children:[(0,n.jsx)("span",{className:"font-medium text-foreground",children:m})," is currently editing"]})})]}):null]}),(0,n.jsx)("div",{className:"text-sm text-muted-foreground truncate",children:e.category||"—"}),(0,n.jsx)("div",{className:"text-sm text-muted-foreground truncate",children:rA(e,em)}),(0,n.jsxs)("div",{className:"text-xs text-muted-foreground leading-snug",children:[(0,n.jsx)("div",{className:"text-foreground font-medium",children:a}),(0,n.jsx)("div",{children:s})]}),(0,n.jsxs)("div",{className:"flex flex-wrap gap-1",children:["trash"===_?(0,n.jsx)(tB,{variant:"outline",className:"text-muted-foreground",children:"In trash"}):null,(0,n.jsx)(tB,{variant:t?"default":r?"secondary":"outline",children:t?"Published":r?"Scheduled":"Draft"})]}),(0,n.jsx)("div",{className:"flex min-w-0 justify-center",children:(0,n.jsx)(rq,{post:e,bodyHtml:eq[e.id],duplicateTitleCounts:ew,bodyLoading:eM})}),(0,n.jsxs)("div",{className:"flex flex-wrap items-center justify-end gap-2",children:[h?(0,n.jsx)(L.Button,{size:"sm",variant:"outline",disabled:!0,title:p,children:"trash"===_?"View":"Edit"}):(0,n.jsx)(L.Button,{asChild:!0,size:"sm",variant:"outline",children:(0,n.jsx)(i.N_,{to:"/admin/blog/".concat(e.id,"/"),children:"trash"===_?"View":"Edit"})}),"trash"===_?(0,n.jsxs)(n.Fragment,{children:[(0,n.jsx)(L.Button,{type:"button",size:"sm",variant:"secondary",onClick:()=>eY.mutate(e.id),disabled:eY.isPending,children:"Restore"}),(0,n.jsx)(L.Button,{type:"button",size:"sm",variant:"destructive",onClick:()=>Y({id:e.id,title:e.title,slug:e.slug}),children:"Delete permanently"})]}):(0,n.jsx)(L.Button,{type:"button",size:"sm",variant:"destructive",disabled:h,title:h?p:void 0,onClick:()=>A({id:e.id,title:e.title,slug:e.slug}),children:"Trash"})]})]},e.id)})})]}),!ee&&ek>0?(0,n.jsx)("nav",{className:"text-sm text-muted-foreground","aria-label":"Admin posts pagination",children:(0,n.jsxs)("div",{className:"flex flex-wrap items-center justify-center gap-x-6 gap-y-2 text-center",children:[(0,n.jsxs)("p",{children:["Showing ",(0,n.jsx)("span",{className:"text-foreground font-medium",children:eP}),"–",(0,n.jsx)("span",{className:"text-foreground font-medium",children:eI})," of"," ",(0,n.jsx)("span",{className:"text-foreground font-medium",children:ek}),eL?(0,n.jsx)("span",{className:"text-muted-foreground",children:" (filtered)"}):null]}),eS>1?(0,n.jsxs)("div",{className:"flex flex-wrap items-center justify-center gap-2",children:[(0,n.jsx)(L.Button,{type:"button",variant:"outline",size:"sm",disabled:eC<=1,onClick:()=>S(e=>Math.max(1,e-1)),children:"Previous"}),(0,n.jsxs)("span",{className:"min-w-[7rem] px-1 tabular-nums sm:min-w-[8.5rem]",children:["Page ",(0,n.jsx)("span",{className:"font-medium text-foreground",children:eC})," of"," ",(0,n.jsx)("span",{className:"font-medium text-foreground",children:eS})]}),(0,n.jsx)(L.Button,{type:"button",variant:"outline",size:"sm",disabled:eC>=eS,onClick:()=>S(e=>Math.min(eS,e+1)),children:"Next"})]}):null]})}):null,(0,n.jsx)(er,{open:!!C,onOpenChange:e=>!e&&A(null),children:(0,n.jsxs)(es,{children:[(0,n.jsxs)(ei,{children:[(0,n.jsx)(eo,{children:"Move this post to trash?"}),(0,n.jsxs)(ed,{children:["It will be removed from the live site and listed under Trash. You can restore it or delete it permanently from there.",(null==C?void 0:C.title)||(null==C?void 0:C.slug)?(0,n.jsx)("span",{className:"block mt-2 text-foreground",children:(0,n.jsx)("span",{className:"font-medium",children:(null==C?void 0:C.title)||"(untitled)"})}):null]})]}),(0,n.jsxs)(el,{children:[(0,n.jsx)(eu,{disabled:eV.isPending,children:"Cancel"}),(0,n.jsx)(ec,{className:"bg-destructive text-destructive-foreground hover:bg-destructive/90",disabled:eV.isPending,onClick:()=>(null==C?void 0:C.id)&&eV.mutate(C.id),children:eV.isPending?"Moving…":"Move to trash"})]})]})}),(0,n.jsx)(er,{open:!!Q,onOpenChange:e=>!e&&Y(null),children:(0,n.jsxs)(es,{children:[(0,n.jsxs)(ei,{children:[(0,n.jsx)(eo,{children:"Delete this post permanently?"}),(0,n.jsxs)(ed,{children:["This cannot be undone. The post will be removed from the database.",(null==Q?void 0:Q.title)?(0,n.jsx)("span",{className:"block mt-2 font-medium text-foreground",children:Q.title}):null]})]}),(0,n.jsxs)(el,{children:[(0,n.jsx)(eu,{disabled:eQ.isPending,children:"Cancel"}),(0,n.jsx)(ec,{className:"bg-destructive text-destructive-foreground hover:bg-destructive/90",disabled:eQ.isPending,onClick:()=>(null==Q?void 0:Q.id)&&eQ.mutate(Q.id),children:eQ.isPending?"Deleting…":"Delete permanently"})]})]})}),(0,n.jsx)(er,{open:G,onOpenChange:W,children:(0,n.jsxs)(es,{children:[(0,n.jsxs)(ei,{children:[(0,n.jsxs)(eo,{children:["Move ",e1.length," post(s) to trash?"]}
1),(0,n.jsx)(ed,{children:"They will be hidden from the site until you restore them from Trash or delete them permanently."})]}),(0,n.jsxs)(el,{children:[(0,n.jsx)(eu,{disabled:eJ.isPending,children:"Cancel"}),(0,n.jsx)(ec,{className:"bg-destructive text-destructive-foreground hover:bg-destructive/90",disabled:eJ.isPending,onClick:()=>{let e=e1.filter(e=>!rT(e,_,ep,null==l?void 0:l.id));if(0===e.length){f({title:"Could not move to trash",description:"Those posts are being edited by another admin.",variant:"destructive"}),W(!1);return}e.length<e1.length&&f({title:"Some posts skipped",description:"Posts locked by another editor were not moved."}),eJ.mutate(e)},children:eJ.isPending?"Moving…":"Move to trash"})]})]})}),(0,n.jsx)(er,{open:H,onOpenChange:V,children:(0,n.jsxs)(es,{children:[(0,n.jsxs)(ei,{children:[(0,n.jsxs)(eo,{children:["Permanently delete ",e1.length," post(s)?"]}),(0,n.jsx)(ed,{children:"This cannot be undone. All selected trashed posts will be removed from the database."})]}),(0,n.jsxs)(el,{children:[(0,n.jsx)(eu,{disabled:eX.isPending,children:"Cancel"}),(0,n.jsx)(ec,{className:"bg-destructive text-destructive-foreground hover:bg-destructive/90",disabled:eX.isPending,onClick:()=>eX.mutate(e1),children:eX.isPending?"Deleting…":"Delete permanently"})]})]})}),(0,n.jsx)(er,{open:J,onOpenChange:$,children:(0,n.jsxs)(es,{children:[(0,n.jsxs)(ei,{children:[(0,n.jsx)(eo,{children:"Empty trash?"}),(0,n.jsxs)(ed,{children:["Permanently delete all ",ev," post(s) in trash. This cannot be undone."]})]}),(0,n.jsxs)(el,{children:[(0,n.jsx)(eu,{disabled:eZ.isPending,children:"Cancel"}),(0,n.jsx)(ec,{className:"bg-destructive text-destructive-foreground hover:bg-destructive/90",disabled:eZ.isPending,onClick:()=>eZ.mutate(ex.map(e=>e.id)),children:eZ.isPending?"Deleting…":"Empty trash"})]})]})})]})},{})}),(0,n.jsx)(s.qh,{path:"blog/:id",element:(0,n.jsx)(function(){var e,t,r,l,d,c,u,m,h,p;let{id:g}=(0,s.g)(),x="new"===g,{user:v}=I(),y=(0,s.Zp)(),j=(0,s.zy)(),w=(0,o.jE)(),_=(0,a.useId)(),N="content-quill-tb-".concat(_.replace(/:/g,"")),{data:k,isLoading:S,error:C}=(0,eK.I)({queryKey:["admin","blog_post",g],queryFn:()=>aw(g),enabled:!x}),{data:A,isLoading:E,refetch:q}=(0,eK.I)({queryKey:["admin","blog_post_edit_lock",g],queryFn:async()=>{let{data:e,error:t}=await T.N.from("blog_post_edit_sessions").select("user_id, updated_at").eq("post_id",g).maybeSingle();if(t)throw t;return e},enabled:!x&&!!g&&!!(null==v?void 0:v.id),staleTime:0,refetchInterval:8e3}),M=(0,a.useMemo)(()=>!x&&!!A&&!!(null==v?void 0:v.id)&&!!aO(A.updated_at)&&A.user_id!==v.id,[x,A,null==v?void 0:v.id]),P=M&&(null==A?void 0:A.user_id)?A.user_id:null,{data:O}=(0,eK.I)({queryKey:["admin","user_presence_label",P],queryFn:async()=>{let{data:e,error:t}=await T.N.rpc("admin_list_users_with_roles",{p_user_id:P});if(t)throw t;return(null==e?void 0:e[0])||null},enabled:!!P}),R=(0,a.useMemo)(()=>{let e="string"==typeof(null==O?void 0:O.display_name)?O.display_name.trim():"";if(e)return e;let t=(null==O?void 0:O.email)||"",r=t.indexOf("@");return r>0?t.slice(0,r):t||"Another admin"},[O]),D=(0,a.useCallback)(async()=>{if(x||!g)return;let{data:e,error:t}=await T.N.from("blog_post_edit_sessions").select("user_id, updated_at").eq("post_id",g).maybeSingle();if(t)throw t;if(e&&aO(e.updated_at)&&e.user_id!==(null==v?void 0:v.id))throw Error("Another admin is editing this post. Try again after they finish or the lock times out.")},[x,g,null==v?void 0:v.id]),{data:B=[]}=(0,eK.I)({queryKey:["admin","blog_categories","names"],queryFn:async()=>{let{data:e,error:t}=await T.N.from("blog_categories").select("name").order("sort_order",{ascending:!0}).order("name",{ascending:!0});if(!t&&(null==e?void 0:e.length))return e.map(e=>String(e.name||"").trim()).filter(Boolean);let{data:r,error:n}=await T.N.from("blog_posts").select("category");return n?[]:[...new Set((r||[]).map(e=>String(e.category||"").trim()).filter(Boolean))].sort((e,t)=>e.localeCompare(t))},staleTime:6e4}),F=(0,a.useMemo)(()=>B,[B]),{data:U=[]}=(0,eK.I)({queryKey:["admin","users_with_roles","author_picker"],queryFn:async()=>{let{data:e,error:t}=await T.N.rpc("admin_list_users_with_roles");if(t)throw t;return(e||[]).sort((e,t)=>
1(e.email||"").localeCompare(t.email||""))},staleTime:6e4}),{data:z=[]}=(0,eK.I)({queryKey:["admin","blog_posts","seo_dup"],queryFn:async()=>{let{data:e,error:t}=await T.N.from("blog_posts").select("id, title, seo_title, deleted_at");if(t)throw t;return e||[]},staleTime:2e4}),{data:K,isSuccess:G}=(0,eK.I)({queryKey:n$,queryFn:nZ,staleTime:6e4}),W=(0,a.useRef)(!1),[H,V]=(0,a.useState)(()=>({...ak})),[Q,Y]=(0,a.useState)(5),[J,$]=(0,a.useState)(3),[X,Z]=(0,a.useState)(!1),[ee,et]=(0,a.useState)(!1),[en,ea]=(0,a.useState)([]),[em,eh]=(0,a.useState)(null),[eg,ex]=(0,a.useState)(!1),[ef,ev]=(0,a.useState)(!1),[ey,eb]=(0,a.useState)(!1),[ej,ew]=(0,a.useState)(null),[e_,eN]=(0,a.useState)("summary"),[ek,eA]=(0,a.useState)(!1),[eE,eT]=(0,a.useState)(!1),[eq,eM]=(0,a.useState)("format_professional"),[eP,eL]=(0,a.useState)(""),[eO,eR]=(0,a.useState)(!1),[eD,eG]=(0,a.useState)(null),[eW,eQ]=(0,a.useState)(0),[eY,eJ]=(0,a.useState)(0),[e1,e4]=(0,a.useState)(!1),[e5,e6]=(0,a.useState)([]),[e8,e7]=(0,a.useState)(!1),[tt,ta]=(0,a.useState)(!1),[to,td]=(0,a.useState)(null),[tc,tu]=(0,a.useState)(null),[tm,th]=(0,a.useState)(null),tg=(0,a.useRef)(null),tx=(0,a.useRef)(null),tf=(0,a.useRef)(null),tv=(0,a.useRef)(null),[ty,tb]=(0,a.useState)("visual"),[tj,tw]=(0,a.useState)("content"),[t_,tN]=(0,a.useState)(!1),tS=(0,a.useRef)(""),[tC,tA]=(0,a.useState)(!1),[tM,tI]=(0,a.useState)(""),tL=(0,a.useRef)({excludePathKeyList:[],allowedPathKeys:new Set,maxInternal:5,maxExternal:3}),tD=(0,a.useRef)(aC(ak)),[tF,tU]=(0,a.useState)(0),tz=(0,a.useCallback)(()=>tU(e=>e+1),[]);(0,a.useEffect)(()=>{let e=()=>eQ(e=>e+1);return window.addEventListener("appar-admin-ai-settings",e),()=>window.removeEventListener("appar-admin-ai-settings",e)},[]),(0,a.useEffect)(()=>{let e=()=>eJ(e=>e+1);return window.addEventListener(nH,e),()=>window.removeEventListener(nH,e)},[]),(0,a.useEffect)(()=>{G&&n1(null!=K?K:null)},[K,G]),(0,a.useEffect)(()=>{tN(!1)},[g]),(0,a.useEffect)(()=>{if(!tC)return;let e=requestAnimationFrame(()=>{var e;return null==(e=document.getElementById("new_category_name"))?void 0:e.focus()});return()=>cancelAnimationFrame(e)},[tC]);let tK=(0,a.useMemo)(()=>no(),[eW]),tG=(0,a.useMemo)(()=>nd(),[eW]),tW=(0,a.useMemo)(()=>a_(H.content).replace(/\s+/g," ").trim().length>=24,[H.content]),tV=(0,a.useMemo)(()=>{let{internalLinkSitemapPaste:e}=nJ();return e3(e).length>0},[eY]),tY=tG&&(Q>0||J>0)&&(0===Q||tV),tJ=(0,a.useCallback)(async e=>{et(!0),eh(null);try{let t=nf(nx(e||"")),r=t.filter(e=>"external"===e.kind).map(e=>e.href),n=new Map;if(r.length>0){let e=new Set(r.map(e=>String(e||"").trim()).filter(Boolean)).size;eh({phase:"verify",completed:0,total:e}),n=await nW(r,{concurrency:3,supabaseClient:T.N,onProgress:e=>eh({phase:"verify",...e})})}else eh({phase:"packaging"});let a=t.map(e=>{var t;return{...e,reachability:"external"===e.kind?null!=(t=n.get(e.href))?t:"unknown":void 0}});ea(a)}finally{eh(null),et(!1)}},[]),t$=(0,a.useMemo)(()=>{let e=String(H.category||"").trim();return e||"__none__"},[H.category]),t4=(0,a.useMemo)(()=>String(H.created_by||"").trim()||"__none__",[H.created_by]),t5=(0,a.useRef)(!1),t3=(0,a.useRef)(null),t6=(0,a.useRef)(null),t8=(0,a.useRef)(Promise.resolve()),rr=(0,a.useRef)(""),rn=(0,a.useRef)(null),rs=(0,a.useRef)(g),ri=(0,a.useRef)(k),rc=(0,a.useRef)(!1);rs.current=g,ri.current=k,rc.current=M;let[ru,rf]=(0,a.useState)(null),rv=(0,a.useRef)(H);rv.current=H;let ry=(0,a.useRef)(x);function rb(e,t){try{sessionStorage.setItem("appar_blog_link_caps_v1",JSON.stringify({maxInternal:e,maxExternal:t}))}catch(e){}}ry.current=x,(0,a.useEffect)(()=>{try{let e=sessionStorage.getItem("appar_blog_link_caps_v1");if(!e)return;let t=JSON.parse(e);"number"==typeof t.maxInternal&&Y(Math.min(20,Math.max(0,t.maxInternal))),"number"==typeof t.maxExternal&&$(Math.min(20,Math.max(0,t.maxExternal)))}catch(e){}},[]);let rj=(0,a.useCallback)(function(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:new Date,t=arguments.length>1?arguments[1]:void 0;rf(e);let r=null!=t?t:rs.current;if(r&&"new"!==r)try{localStorage.setItem(aE(r),e.toISOString())}catch(e){}},[]);(0,a.useRef)(rj).current=rj,(0,a.useEffect)(()=>
1{if(x)return void rf(null);if(!(null==k?void 0:k.id))return;let e=k.updated_at?new Date(k.updated_at):null,t=e&&!Number.isNaN(e.getTime())?e.getTime():null;try{let e=localStorage.getItem(aE(k.id));if(e){let r=new Date(e).getTime();!Number.isNaN(r)&&(null==t||r>t)&&(t=r)}}catch(e){}rf(null!=t?new Date(t):null)},[x,null==k?void 0:k.id,null==k?void 0:k.updated_at]);let rw=(0,a.useRef)(new Set),r_=(0,a.useRef)({promise:null});(0,a.useEffect)(()=>{if(k){if(rw.current.has(k.id)){rw.current.delete(k.id),tD.current=aC(rv.current),rr.current=tD.current,tz(),t5.current=!0;return}V(e=>{var t,r;let n={...e,...k,cover_image_url:k.cover_image_url||"",canonical_url:k.canonical_url||"",robots_index:null==(t=k.robots_index)||t,robots_follow:null==(r=k.robots_follow)||r,og_image_url:k.og_image_url||"",twitter_image_url:k.twitter_image_url||"",scheduled_at:k.published_at?new Date(k.published_at).toISOString().slice(0,16):"",created_by:null!=k.created_by?String(k.created_by):""};for(let e of["title","slug","excerpt","category","content","seo_title","seo_description","focus_keyword","meta_keywords","og_title","og_description","twitter_title","twitter_description"])null==n[e]&&(n[e]="");{let e=String(k.seo_schema_type||"").trim();n.seo_schema_type=eU.includes(e)?e:"BlogPosting"}return tD.current=aC(n),rr.current=tD.current,tz(),n}),t5.current=!0}},[k,tz]),(0,a.useEffect)(()=>{!x&&k&&(null==v?void 0:v.id)&&(k.created_by||V(e=>e.created_by?e:{...e,created_by:v.id}))},[x,null==k?void 0:k.id,null==k?void 0:k.created_by,null==v?void 0:v.id]),(0,a.useEffect)(()=>{if(!x){W.current=!1;return}(null==v?void 0:v.id)&&(W.current||V(e=>e.created_by?(W.current=!0,e):(W.current=!0,{...e,created_by:v.id})))},[x,null==v?void 0:v.id]),(0,a.useEffect)(()=>{var e;if(!x||t5.current)return;if(null==(e=j.state)?void 0:e.blankNewPost){localStorage.removeItem(aA),localStorage.removeItem(aT),W.current=!!(null==v?void 0:v.id);let e={...ak,...(null==v?void 0:v.id)?{created_by:v.id}:{}};V(e),tD.current=aC(e),rr.current=tD.current,tz(),t5.current=!0,y("/admin/blog/new/",{replace:!0,state:{}});return}let t=localStorage.getItem(aA);if(!t){tD.current=aC(ak),rr.current=tD.current,tz(),t5.current=!0;return}try{let e=JSON.parse(t);V(()=>{let t={...ak,...e};return!String(t.meta_keywords||"").trim()&&String(e.tags||"").trim()&&(t.meta_keywords=String(e.tags).trim()),"tags"in t&&delete t.tags,tD.current=aC(t),rr.current=tD.current,tz(),t});try{localStorage.removeItem(aA),localStorage.removeItem(aT)}catch(e){}}catch(e){tD.current=aC(ak),rr.current=tD.current,tz()}t5.current=!0},[x,null==(e=j.state)?void 0:e.blankNewPost,y,tz,null==v?void 0:v.id]);let rN=(0,a.useMemo)(()=>{let e=H.slug||"";return e?"".concat(eS.W6,"/").concat(e,"/"):""},[H.slug]),rk=(0,a.useMemo)(()=>{if(x||!g)return"";try{return new URL("/preview/blog/".concat(g,"/"),window.location.origin).toString()}catch(e){return"/preview/blog/".concat(g,"/")}},[g,x]);(0,a.useEffect)(()=>{if(x||!g||!(null==v?void 0:v.id)||E||M)return;let e=v.id,t=!1,r=!1,n=async()=>{if(t)return;let{data:e,error:r}=await T.N.rpc("touch_blog_post_edit_lock",{p_post_id:g});if(r)return void console.warn("[edit presence] touch failed:",r.message);!1===e&&q()};(async()=>{if(t)return;let{data:e,error:n}=await T.N.rpc("claim_blog_post_edit_lock",{p_post_id:g});return n?console.warn("[edit presence] claim failed:",n.message):e&&!1===e.ok?q():!r&&(r=!0,w.invalidateQueries({queryKey:["admin","blog_posts"]}))})();let a=setInterval(n,25e3),s=()=>{"visible"===document.visibilityState&&n()};return document.addEventListener("visibilitychange",s),()=>{t=!0,clearInterval(a),document.removeEventListener("visibilitychange",s),T.N.from("blog_post_edit_sessions").delete().match({post_id:g,user_id:e}).then(()=>{w.invalidateQueries({queryKey:["admin","blog_posts"]})})}},[x,g,null==v?void 0:v.id,w,E,M,q]);let rS=(0,a.useRef)(null),rC=(0,tO.n)({mutationFn:async e=>{if(x||await D(),x){let t={...e},r=r_.current;if(r.promise){let e=await r.promise,{data:n,error:a}=await T.N.from("blog_posts").update(t).eq("id",e.id).select("*").single();if(a)throw a;return n}let n=T.N.from("blog_posts").insert(t).select("*").single().then(e=>{let{data:t,error:r}=e;if(r)throw r;return(null==t?void 0:t.id)&&(rw.current.add(t.id),window.setTimeout(()=>rw.current.delete(t.id),4e3)),t});return r.promise=n.finally(()=>{r.promise=null}),n}let{data:t,error:r}=await T.N.from("blog_posts").update(e).eq("id",g).select("*").single();if(r)throw r;return t},onSuccess:async e=>{await w.invalidateQueries({queryKey:["admin","blog_posts"]}),(null==e?void 0:e.id)&&(rj(new Date,e.id),x?w.setQueryData(["admin","blog_post",e.id],e):await w.invalidateQueries({queryKey:["admin","blog_post",e.id]})),x&&(null==e?void 0:e.id)&&y("/admin/blog/".concat(e.id,"/"),{replace:!0})}});rS.current=rC.mutateAsync;let rA=(0,tO.n)({mutationFn:async()=>{await D();let e=new Date().toISOString(),{error:t}=await T.N.from("blog_posts").update({deleted_at:e,updated_at:e}).eq("id",g);if(t)throw t},onSuccess:async()=>{await w.invalidateQueries({queryKey:["admin","blog_posts"]}),await w.invalidateQueries({queryKey:["public","blog_posts"]}),y("/admin/blog/",{replace:!0}),f({title:"Moved to trash",description:"Restore or permanently delete it from Trash."})},onError:e=>{f({title:"Could not move to trash",description:(0,T.z)(e)||"Try again.",variant:"destructive"})}}),rE=(0,tO.n)({mutationFn:async e=>{await D();let t={published_at:e?new Date().toISOString():null},{data:r,error:n}=await T.N.from("blog_posts").update(t).eq("id",g).select("*").single();if(n)throw n;return r},onSuccess:async e=>{await w.invalidateQueries({queryKey:["admin","blog_posts"]}),await w.invalidateQueries({queryKey:["admin","blog_post",g]}),(null==e?void 0:e.published_at)?rT("scheduled_at",new Date(e.published_at).toISOString().slice(0,16)):rT("scheduled_at",""),rj()}});function rT(e,t){V(r=>({...r,[e]:t}))}let rq=(0,tO.n)({mutationFn:async e=>{let t=String(e||"").trim();if(!t)throw Error("Enter a category name.");let{data:r,error:n}=await T.N.from("blog_categories").select("id").eq("name",t).maybeSingle();if(n)throw n;if(r)throw Error("A category with that name already exists.");let{data:a,error:s}=await T.N.from("blog_categories").select("sort_order");if(s)throw s;let i=(null==a?void 0:a.length)?Math.max(0,...a.map(e=>Number(e.sort_order)||0)):0,l=ab(t);l||(l="category-".concat(i+1));let o=l,{data:d}=await T.N.from("blog_categories").select("id").eq("slug",o).maybeSingle();d&&(o="".concat(l,"-").concat(Date.now().toString(36)));let{data:c,error:u}=await T.N.from("blog_categories").insert({name:t,slug:o,sort_order:i+1}).select("name").single();if(u)throw u;return String((null==c?void 0:c.name)||t).trim()},onSuccess:e=>{w.invalidateQueries({queryKey:["admin","blog_categories","names"]}),w.invalidateQueries({queryKey:["admin","blog_categories","rows"]}),rT("category",e),tA(!1),tI(""),f({title:"Category added",description:"".concat(e," is selected for this post.")})},onError:e=>{f({title:"Could not add category",description:(0,T.z)(e)||(null==e?void 0:e.message)||"Try again.",variant:"destructive"})}}),rM=(0,a.useCallback)(e=>{tg.current=e,e7(!0)},[]),rI=(0,a.useCallback)(e=>{let t=tg.current;if(tg.current=null,!t||!e)return;let r=t.getSelection(!0),n=r?r.index:t.getLength();t.insertEmbed(n,"image",e,"user"),t.setSelection(n+1,0,"silent")},[]),rO=(0,a.useMemo)(()=>
1tc?[{objectPath:tc,storageUrl:eI(tc,T.N)}]:[],[tc]),rR=(0,tO.n)({mutationFn:async e=>{let{error:t}=await T.N.storage.from(eC).remove([e]);if(t)throw t;await eH(e)},onSuccess:async(e,t)=>{V(e=>({...e,content:function(e,t){if(!e||!t||"undefined"==typeof DOMParser)return e||"";try{let r=new DOMParser().parseFromString(e,"text/html");return r.querySelectorAll("img[src]").forEach(e=>{eF(e.getAttribute("src")||"")===t&&e.remove()}),r.body.innerHTML}catch(t){return e||""}}(e.content||"",t),cover_image_url:aD(e.cover_image_url,t)?"":e.cover_image_url,og_image_url:aD(e.og_image_url,t)?"":e.og_image_url,twitter_image_url:aD(e.twitter_image_url,t)?"":e.twitter_image_url})),await w.invalidateQueries({queryKey:["admin","cms-media",eC]}),await w.invalidateQueries({queryKey:["admin","cms-media-meta"]}),f({title:"File removed",description:"Removed from storage. Matching images were removed from this post body and cleared from cover/social fields if they used this file."}),th(null)},onError:e=>{f({title:"Delete failed",description:(null==e?void 0:e.message)||"Check storage policies.",variant:"destructive"})}}),rD=(0,a.useCallback)(e=>{let t=String((null==e?void 0:e.src)||"").trim();if(!t)return;let r=eF(eB(t)||t)||eF(t);if(!r)return void f({title:"Not a library image",description:"Attachment details apply only to images in your Media Library (Supabase storage). Use the image button to add library uploads."});tu(r)},[]),rU=(0,a.useCallback)(()=>{w.invalidateQueries({queryKey:["admin","cms-media",eC]})},[w]),rz=(0,a.useCallback)(async()=>{let e=H.content||"",t=n6(e);if(0===t.length)return void f({title:"No external images to import",description:"Only hotlinked http(s) images are processed. Data URLs, same-site paths, and images already on your Media Library are skipped."});ta(!0),td({completed:0,total:t.length,currentUrl:null});try{let r=await n8(e,T.N,{onProgress:td});rT("content",r.html),await w.invalidateQueries({queryKey:["admin","cms-media",eC]});let n=r.failed.length,a=["Imported ".concat(r.imported," of ").concat(t.length," image(s) into storage."),n?"".concat(n," failed (often blocked: other sites do not allow cross-origin download in the browser)."):""].filter(Boolean);f({title:r.imported>0?"External images re-hosted":"Import finished",description:a.join(" "),variant:n&&0===r.imported?"destructive":"default"})}catch(e){f({title:"Import failed",description:(null==e?void 0:e.message)||"Unknown error",variant:"destructive"})}finally{td(e=>e?{completed:e.total,total:e.total,currentUrl:null}:null),await new Promise(e=>setTimeout(e,500)),td(null),ta(!1)}},[H.content,w,T.N]),rG=(0,a.useCallback)(()=>{tS.current=H.slug,tN(!0),requestAnimationFrame(()=>{var e;return null==(e=document.getElementById("slug"))?void 0:e.focus()})},[H.slug]),rQ=(0,a.useCallback)(()=>{rT("slug",tS.current),tN(!1)},[]),rY=(0,a.useCallback)(()=>{let e=String(H.slug||"").trim();rT("slug",(e?ab(e):tS.current)||tS.current),tN(!1)},[H.slug]),rJ=(0,a.useMemo)(()=>({clipboard:{matchVisual:!1}}),[]),r$=(0,a.useMemo)(()=>({words:a_(H.content).trim().split(/\s+/).filter(Boolean).length,readTime:function(e){let t=Math.max(1,Math.round(a_(e).trim().split(/\s+/).filter(Boolean).length/200));return"".concat(t," min read")}(H.content)}),[H.content]),rX=(0,a.useMemo)(()=>{var e,t=null!=(e=null==k?void 0:k.published_at)?e:null;if(!t)return{hasDate:!1,isLive:!1,isScheduled:!1};let r=new Date(t).getTime();if(Number.isNaN(r))return{hasDate:!1,isLive:!1,isScheduled:!1};let n=Date.now();return{hasDate:!0,isLive:r<=n,isScheduled:r>n}},[null==k?void 0:k.published_at]),rZ=(0,a.useMemo)(()=>x||!rX.hasDate?{label:"Draft",className:"shrink-0 rounded-full border-transparent bg-muted text-muted-foreground dark:bg-muted/80 dark:text-foreground/90"}:rX.isScheduled?{label:"Scheduled",className:"shrink-0 rounded-full border-transparent bg-sky-100 text-sky-950 dark:bg-sky-950/50 dark:text-sky-50"}:{label:"Published",className:"shrink-0 rounded-full border-transparent bg-emerald-100 text-emerald-950 dark:bg-emerald-950/55 dark:text-emerald-50"},[x,rX.hasDate,rX.isScheduled,rX.isLive]);function r0(e,t){var r,n,a;let s=null!=t?t:H,i=aj(s,{isNew:x,existingSlug:null==k?void 0:k.slug}
1),l={title:(null==(r=s.title)?void 0:r.trim())||null,slug:i,excerpt:s.excerpt||null,category:s.category||null,cover_image_url:s.cover_image_url||null,featured:!!s.featured,content:s.content||null,seo_title:s.seo_title||null,seo_description:s.seo_description||null,focus_keyword:s.focus_keyword||null,meta_keywords:(null==(n=s.meta_keywords)?void 0:n.trim())||null,canonical_url:s.canonical_url||null,robots_index:!!s.robots_index,robots_follow:!!s.robots_follow,og_title:s.og_title||null,og_description:s.og_description||null,og_image_url:s.og_image_url||null,twitter_title:s.twitter_title||null,twitter_description:s.twitter_description||null,twitter_image_url:s.twitter_image_url||null,seo_schema_type:(()=>{let e=String(s.seo_schema_type||"").trim();return eU.includes(e)&&"BlogPosting"!==e?e:null})(),updated_at:new Date().toISOString(),created_by:(null==(a=s.created_by)?void 0:a.trim())?s.created_by.trim():null,author_display_name:aI(s,U,k)};if(e){let e=String(s.scheduled_at||"").trim();if(e){let t=new Date(e),r=t.getTime(),n=Date.now(),a=(null==k?void 0:k.published_at)?new Date(k.published_at).getTime():NaN,s=!Number.isNaN(a)&&a<=n;x||!s||r>n?l.published_at=t.toISOString():l.published_at=new Date().toISOString()}else l.published_at=null}return l}let r1=(0,a.useRef)(null);r1.current=r0,rn.current=async function(){let e=rs.current;if(ry.current||!e||"new"===e||!ri.current)return;await D();let t=r0(!1,rv.current),{error:r}=await T.N.from("blog_posts").update(t).eq("id",e);if(r)throw r;t3.current=new Date,rj()};let r2=(0,a.useCallback)(()=>{try{let e=JSON.parse(tD.current);V(t=>({...t,...e}))}catch(e){V({...ak})}},[]),r4=(0,a.useCallback)(async()=>{let e=r0(!0);e.published_at=null,await rC.mutateAsync(e),t3.current=new Date;try{localStorage.removeItem(aA),localStorage.removeItem(aT),g&&"new"!==g&&(localStorage.removeItem(aM(g)),localStorage.removeItem(aq(g)))}catch(e){}V(e=>{let t={...e,scheduled_at:""};return tD.current=aC(t),rr.current=tD.current,t}),tz(),rj(),f({title:"Saved as draft",description:"Publish schedule cleared; the post stays unpublished until you set a date and save again."})},[tz,x,rj,rC,H.featured,H.created_by,H.scheduled_at,H.canonical_url,H.category,H.content,H.cover_image_url,H.excerpt,H.focus_keyword,H.meta_keywords,H.og_description,H.og_image_url,H.og_title,H.robots_follow,H.robots_index,H.seo_description,H.seo_title,H.slug,H.title,H.twitter_description,H.twitter_image_url,H.twitter_title,null==k?void 0:k.slug,g]),r5=(0,a.useCallback)(async()=>{var e;let t=r0(!0),r=!x&&(null==k?void 0:k.slug)||"",n=await rC.mutateAsync(t);if(t3.current=new Date,!x&&r&&t.slug&&t.slug!==r)try{await T.N.from("redirects").upsert({from_path:"/".concat(r,"/"),to_path:"/".concat(t.slug,"/"),redirect_type:301},{onConflict:"from_path"}),w.invalidateQueries({queryKey:["public","redirects"]})}catch(e){}try{localStorage.removeItem(aA),localStorage.removeItem(aT);let e=(null==n?void 0:n.id)||g;e&&"new"!==e&&(localStorage.removeItem(aM(e)),localStorage.removeItem(aq(e)))}catch(e){}V(e=>{let t={...e,...(null==n?void 0:n.published_at)?{scheduled_at:new Date(n.published_at).toISOString().slice(0,16)}:{scheduled_at:""}};return tD.current=aC(t),rr.current=tD.current,t}),tz(),rj();let a=null!=(e=null==n?void 0:n.published_at)?e:t.published_at;if(a){let e=new Date(a).getTime();if(Number.isNaN(e))return;e>Date.now()?f({title:"Post scheduled",description:"Goes live ".concat(aN(a),".")}):f({title:"Post published",description:"Visible on the blog now."})}else f({title:"Saved as draft",description:"Not published — set a date below and save to schedule or publish."})},[tz,rj,H.featured,H.created_by,H.scheduled_at,x,rC,H.canonical_url,H.category,H.content,H.cover_image_url,H.excerpt,H.focus_keyword,H.meta_keywords,H.og_description,H.og_image_url,H.og_title,H.robots_follow,H.robots_index,H.seo_description,H.seo_title,H.slug,H.title,H.twitter_description,H.twitter_image_url,H.twitter_title,null==k?void 0:k.published_at,null==k?void 0:k.slug,g,w]);function r3(e,t){let{excludePathKeyList:r,allowedPathKeys:n,maxInternal:a,maxExternal:s}=tL.current,i=e.filter(e=>!ti(e.path)).length,l=e.filter(e=>ti(e.path)).length,{html:o,added:d,links:c,skipped:u=[]}=function(e,t){let{suggestions:r,maxLinks:n=5,maxInternalLinks:a,maxExternalLinks:s,excludePaths:i=new Set,allowedPathKeys:l=null}=t,o=null!=a||null!=s,d=o?null!=a?a:0:n,c=o&&null!=s?s:0;if(!e||!(null==r?void 0:r.length)||d<=0&&c<=0)return{html:e||"",added:0,links:[],skipped:[]};let u=new DOMParser().parseFromString('<div id="il-root">'.concat(e,"</div>"),"text/html"),m=u.getElementById("il-root");
1if(!m)return{html:e,added:0,links:[],skipped:[]};let h=new Set([...i].map(eX)),p=new Set,g=new Set,x=[],f=[],v=r.map(e=>({path:String(e.path||"").trim(),anchorText:String(e.anchorText||e.anchor||"").trim()})).filter(e=>!(e.anchorText.length<3)&&(!!ti(e.path)||e.path.startsWith("/")&&!e.path.startsWith("//"))),y=0,b=0;for(let{path:e,anchorText:t}of v){if(ti(e)){if(b>=c){f.push({path:e,anchorText:t,reason:"external_cap"});continue}let r=e0(e),n=tl(r);if(!n){f.push({path:e,anchorText:t,reason:"invalid_url"});continue}if(g.has(n)){f.push({path:e,anchorText:t,reason:"url_already_used"});continue}let a=te(m,{includeWhitespace:!0}),s=a.map(e=>e.nodeValue||"").join(""),i=e9(s,t);if(!i){let e=tr(m,t,r);if(e){g.add(n),x.push({path:r,phrase:e.matchedText}),b+=1;continue}tn(m,t),i=e9(s=(a=te(m,{includeWhitespace:!0})).map(e=>e.nodeValue||"").join(""),t)}if(!i){f.push({path:r,anchorText:t,reason:"phrase_not_in_editor"});continue}let l=s.slice(i.start,i.end);if(!ts(u,a,i.start,i.end,r)){f.push({path:r,anchorText:t,reason:"insert_failed"});continue}g.add(n),x.push({path:r,phrase:l}),b+=1;continue}if(y>=d){f.push({path:e,anchorText:t,reason:"internal_cap"});continue}let r=e2(e),n=eX(r);if(h.has(n)){f.push({path:e,anchorText:t,reason:"excluded_path"});continue}if(p.has(n)){f.push({path:e,anchorText:t,reason:"path_already_used"});continue}if(l&&!l.has(n)){f.push({path:e,anchorText:t,reason:"not_in_allowlist"});continue}let a=te(m,{includeWhitespace:!0}),s=a.map(e=>e.nodeValue||"").join(""),i=e9(s,t);if(!i){let e=tr(m,t,r);if(e){p.add(n),x.push({path:r,phrase:e.matchedText}),y+=1;continue}tn(m,t),i=e9(s=(a=te(m,{includeWhitespace:!0})).map(e=>e.nodeValue||"").join(""),t)}if(!i){f.push({path:r,anchorText:t,reason:"phrase_not_in_editor"});continue}let o=s.slice(i.start,i.end);if(!ts(u,a,i.start,i.end,r)){f.push({path:r,anchorText:t,reason:"insert_failed"});continue}p.add(n),x.push({path:r,phrase:o}),y+=1}return{html:m.innerHTML,added:y+b,links:x,skipped:f}}(H.content||"",{suggestions:e,maxInternalLinks:Math.max(a,i),maxExternalLinks:Math.max(s,l),excludePaths:new Set(r),allowedPathKeys:n});if(0===d){let t=u.length>0?" ".concat(u.slice(0,3).map(e=>"phrase_not_in_editor"===e.reason?'"'.concat(e.anchorText,'" not found as editable text'):"not_in_allowlist"===e.reason?"".concat(e.path," not in your sitemap list"):"excluded_path"===e.reason?"".concat(e.path," excluded"):"invalid_url"===e.reason?"".concat(e.path," invalid URL"):"url_already_used"===e.reason?"duplicate ".concat(e.path):"external_cap"===e.reason||"internal_cap"===e.reason?"cap":"".concat(e.anchorText," → ").concat(e.path)).join("; ")).concat(u.length>3?"…":""):"";f({title:"No links inserted",description:0===e.length?"Nothing to apply.":"Those suggestions could not be applied.".concat(t," Fix spacing or wording in the article, or run Analyze again.")});return}rT("content",o);let m=c.filter(e=>!ti(e.path)).length,h=c.length-m,p=[];m>0&&p.push("".concat(m," internal")),h>0&&p.push("".concat(h," external"));let g=p.length?" (".concat(p.join(", "),")"):"",x=c.slice(0,4).map(e=>'"'.concat(e.phrase,'" → ').concat(e.path)).join(" \xb7 ")+(c.length>4?"…":"");if(u.length>0){let e=u.slice(0,2).map(e=>"phrase_not_in_editor"===e.reason?'"'.concat(e.anchorText,'" not found'):"not_in_allowlist"===e.reason?"".concat(e.path," not in allowlist"):'"'.concat(e.anchorText,'" skipped')).join("; ");x+=" — skipped ".concat(u.length,": ").concat(e).concat(u.length>2?"…":"")}f({title:"".concat(t,": added ").concat(d," link").concat(1===d?"":"s").concat(g),description:x}),tJ(o)}async function r8(){if(!nd())return void f({title:"AI not configured",description:"Open Admin → API Settings and add the API key for your chosen provider (or VITE_GEMINI_API_KEY for Gemini only)."});let e=Math.min(20,Math.max(0,Number(Q)||0)),t=Math.min(20,Math.max(0,Number(J)||0));if(e+t<1)return void f({title:"Set link counts",description:"Increase max internal or max external (at least one should be above zero)."});let{internalLinkSitemapPaste:r}=nJ(),n=e>0?e3(r):[];if(e>0&&!n.length)return void f({title:"No sitemap added",description:"Go to Auto Linking, paste your sitemap or URL list, and click Save. Or set max internal links to 0 to only add external links."});let a=String(H.content||"").replace(/<[^>]+>/g,"").trim();if(!a)return void f({title:"Add some content first",description:"Write body text so the model can read the full post and pick anchors."});let{provider:s,apiKeys:i,model:l}=no(),o=aj(H,{isNew:x,existingSlug:null==k?void 0:k.slug}),d=o?[eX("/".concat(o,"/"))]:[];Z(!0),eh({phase:"ai"});try{let{internal:r,external:o}=await nq({provider:s,apiKeys:i,model:l,plainText:a,targets:n,maxInternal:e,maxExternal:t,excludePathKeys:d}),c=r6(s),u=o.map(e=>({anchorText:e.anchorText,path:e0(e.path)})),m=u.map(e=>e.path),h=new Set(m.map(e=>
1String(e||"").trim()).filter(Boolean)).size;h>0?eh({phase:"verify",completed:0,total:h}):eh({phase:"packaging"});let p=u.length>0?await nW(m,{supabaseClient:T.N,onProgress:e=>{let{completed:t,total:r}=e;eh({phase:"verify",completed:t,total:r})}}):new Map,g=0,x=[],v=0;for(let e of r)x.push({id:g++,kind:"internal",path:eZ(e.path),anchorText:e.anchorText,selected:!0,verifyStatus:"ok"});for(let e of u){let t=p.get(e.path)||"unknown";if("bad"===t){v+=1;continue}x.push({id:g++,kind:"external",path:e.path,anchorText:e.anchorText,selected:"ok"===t,verifyStatus:t})}if(v>0&&f({title:"Some external URLs skipped",description:"".concat(v," suggestion(s) looked unreachable (HTTP error or not found). They were not added to the list.")}),!x.length)return void f({title:"No AI suggestions",description:"".concat(c," returned nothing usable. Try another model, adjust counts, or expand your sitemap for internal links.")});tL.current={excludePathKeyList:d.map(e=>eX(e)),allowedPathKeys:n.length?new Set(n.map(e=>eX(e.path))):null,maxInternal:e,maxExternal:t},e6(x),e4(!0)}catch(e){f({title:"AI linking failed",description:(null==e?void 0:e.message)||String(e)})}finally{Z(!1),eh(null)}}async function r9(){if(!nd())return void f({title:"AI not configured",description:"In Admin → API Settings, pick the provider under “Internal & external links” and add at least one API key for that provider. (Gemini via build only: VITE_GEMINI_API_KEY.)"});if(a_(H.content).replace(/\s+/g," ").trim().length<24)return void f({title:"Add body content first",description:"Write the article so the model can summarize it into an excerpt (about 150 characters)."});let{provider:e,apiKeys:t,model:r}=no();ex(!0);try{let n=await nO({provider:e,apiKeys:t,model:r,htmlContent:H.content||""});rT("excerpt",n),f({title:"Excerpt generated",description:"".concat(r6(e)," — max 150 characters. Edit the field if you want to tweak it.")})}catch(e){f({title:"Could not generate excerpt",description:(null==e?void 0:e.message)||String(e),variant:"destructive"})}finally{ex(!1)}}async function r7(){if(!nd())return void f({title:"AI not configured",description:"In Admin → API Settings, pick the provider under “Internal & external links” and add at least one API key for that provider."});let e=tv.current;if(!e)return void f({title:"Selection expired",description:"Close the wizard, select text in the editor again, and reopen Content wizard.",variant:"destructive"});if(a_(e.html).replace(/\s+/g," ").trim().length<12)return void f({title:"Selection too short",description:"Select more text and open the wizard again.",variant:"destructive"});if("custom"===eq&&!eP.trim())return void f({title:"Custom instructions required",description:"Describe what you want (e.g. “Turn this into bullets” or “Shorten this section”)."});let{provider:t,apiKeys:r,model:n}=no();eT(!0),eG(null);try{let a=await nU({provider:t,apiKeys:r,model:n,htmlContent:e.html,postTitle:H.title||"",mode:eq,customInstruction:"custom"===eq?eP:"",selectionFragment:!0,timeoutMs:9e4}),s=e$.A.sanitize(a);if(!s.trim())throw Error("Sanitized output was empty — try different instructions.");eG(s)}catch(e){f({title:"Content wizard failed",description:(null==e?void 0:e.message)||String(e),variant:"destructive"})}finally{eT(!1)}}async function ne(){if(!(null==eD?void 0:eD.trim()))return;let e=document.createElement("div");e.innerHTML=eD;let t=(e.innerText||e.textContent||"").trim();try{await navigator.clipboard.writeText(t),f({title:"Copied",description:"Preview text copied to the clipboard."})}catch(e){f({title:"Copy failed",description:"Your browser blocked clipboard access.",variant:"destructive"})}}async function nt(){if(!nd())return void f({title:"AI not configured",description:"In Admin → API Settings, pick the provider under “Internal & external links” and add at least one API key for that provider. (Gemini via build only: VITE_GEMINI_API_KEY.)"});if(a_(H.content).replace(/\s+/g," ").trim().length<24)return void f({title:"Add body content first",description:"The model needs article text to suggest SEO title, meta description, and keywords."});let{provider:e,apiKeys:t,model:r}=no();ev(!0);try{let n=await tk({provider:e,apiKeys:t,model:r,htmlContent:H.content||"",postTitle:H.title||""});rT("seo_title",n.seo_title),rT("seo_description",n.meta_description),rT("focus_keyword",n.focus_keyword),rT("meta_keywords",n.meta_keywords),f({title:"SEO fields generated",description:"".concat(r6(e)," — title ≤").concat(tp.seoTitleMax," chars, description ≤").concat(tp.metaDescriptionMax," (SERP-oriented). Edit as needed.")})}catch(e){f({title:"Could not generate SEO fields",description:(null==e?void 0:e.message)||String(e),variant:"destructive"})}finally{ev(!1)}}
1let nr=(H.seo_title||H.title||"").slice(0,70),nn=(H.seo_description||H.excerpt||"").slice(0,160),na=(0,a.useMemo)(()=>({title:H.title,seo_title:H.seo_title,seo_description:H.seo_description,excerpt:H.excerpt,cover_image_url:H.cover_image_url,og_image_url:H.og_image_url,twitter_image_url:H.twitter_image_url}),[H.title,H.seo_title,H.seo_description,H.excerpt,H.cover_image_url,H.og_image_url,H.twitter_image_url]),ns=(0,a.useMemo)(()=>(function(e,t){let r=(e||[]).filter(e=>!e.deleted_at).map(e=>t.currentPostId&&e.id===t.currentPostId?{...e,title:t.draftTitle,seo_title:t.draftSeoTitle}:e);return tq(t.isNew?[...r,{id:"__editor_new__",title:t.draftTitle,seo_title:t.draftSeoTitle}]:r)})(z,{isNew:x,currentPostId:!x&&g&&"new"!==g?g:null,draftTitle:H.title,draftSeoTitle:H.seo_title}),[z,x,g,H.title,H.seo_title]),ni=(0,a.useMemo)(()=>tP(na,H.content||"",ns),[na,H.content,ns]),nl=(0,a.useMemo)(()=>{let e=String(H.slug||"").trim()||"your-post-slug",t={...H,author_display_name:aI(H,U,k)||"",published_at:(null==k?void 0:k.published_at)||null,updated_at:(null==k?void 0:k.updated_at)||new Date().toISOString()},r=ez({siteUrl:eS.W6,siteName:eS.yy,slug:e,post:t});return r?JSON.stringify(r,null,2):""},[H.slug,H.title,H.seo_title,H.seo_description,H.excerpt,H.content,H.category,H.meta_keywords,H.cover_image_url,H.og_image_url,H.canonical_url,H.seo_schema_type,H.created_by,U,k]),nc=tE(na).length,nu=tT(na).length;async function nm(){if(!nd())return void f({title:"AI not configured",description:"In Admin → API Settings, pick the provider under “Internal & external links” and add at least one API key for that provider."});if(0===ni.issues.length+ni.hints.length)return void f({title:"Nothing to fix",description:"SEO health shows no issues or hints."});if(a_(H.content||"").replace(/\s+/g," ").trim().length<12)return void f({title:"Add body content first",description:"Include article text so the AI can align fixes with your post."});let{provider:e,apiKeys:t,model:r}=no();eb(!0),eN("summary");try{let n=await n_({provider:e,apiKeys:t,model:r,postTitle:H.title||"",seo_title:H.seo_title,seo_description:H.seo_description,excerpt:H.excerpt,contentHtml:H.content||"",issues:ni.issues,hints:ni.hints});ew(n),f({title:"Fix preview ready",description:"Review the result, then apply to the editor if it looks correct."})}catch(e){f({title:"AI SEO fix failed",description:(null==e?void 0:e.message)||String(e),variant:"destructive"})}finally{eb(!1)}}return(ep({isDirty:(0,a.useMemo)(()=>!!t5.current&&aC(H)!==tD.current,[H,tF]),variant:"blog",onSave:r5,onSaveDraft:r4,onDiscard:r2}),(0,a.useEffect)(()=>{if(t5.current)return t6.current&&clearTimeout(t6.current),t6.current=setTimeout(()=>{t8.current=t8.current.then(async()=>{if(t5.current&&!rc.current&&aC(rv.current)!==rr.current)try{var e,t;if(ry.current){let t=r1.current;if(!t)return;let r={...t(!1,rv.current),published_at:null};await (null==(e=rS.current)?void 0:e.call(rS,r))}else await (null==(t=rn.current)?void 0:t.call(rn));rr.current=aC(rv.current),ry.current&&(t3.current=new Date)}catch(e){}}).catch(()=>{})},800),()=>{t6.current&&clearTimeout(t6.current)}},[x,g,H.title,H.slug,H.excerpt,H.category,H.meta_keywords,H.cover_image_url,H.featured,H.created_by,H.content,H.seo_title,H.seo_description,H.focus_keyword,H.canonical_url,H.robots_index,H.robots_follow,H.og_title,H.og_description,H.og_image_url,H.twitter_title,H.twitter_description,H.twitter_image_url,H.scheduled_at,H.seo_schema_type,M,tF]),!x&&E)?(0,n.jsx)("div",{className:"space-y-6",children:(0,n.jsx)("p",{className:"text-sm text-muted-foreground",children:"Checking edit lock…"})}):!x&&M?(0,n.jsxs)("div",{className:"space-y-6 max-w-xl",children:[(0,n.jsxs)("p",{className:"text-sm text-muted-foreground",children:[(0,n.jsx)(i.N_,{to:"/admin/blog/",className:"hover:underline",children:"Blog"})," ","/ Edit post"]}),(0,n.jsxs)("div",{className:"rounded-2xl border bg-card p-6 space-y-4",children:[(0,n.jsxs)("div",{className:"flex items-start gap-3",children:[(0,n.jsx)("div",{className:"rounded-full bg-muted p-2 shrink-0",children:(0,n.jsx)(rx.A,{className:"h-5 w-5 text-muted-foreground","aria-hidden":!0})}),(0,n.jsxs)("div",{className:"space-y-2 min-w-0",children:[(0,n.jsx)("h1",{className:"text-xl font-semibold",children:"Someone else is editing this post"}),(0,n.jsxs)("p",{className:"text-sm text-muted-foreground",children:[(0,n.jsx)("span",{className:"font-medium text-foreground",children:R})," has it open in the editor. You can’t make changes until they close it or leave (the lock clears about a minute after their last activity)."]})]})]}),(0,n.jsxs)("div",{className:"flex flex-wrap gap-2",children:[(0,n.jsx)(L.Button,{type:"button",variant:"outline",onClick:()=>q(),children:"Check again"}),(0,n.jsx)(L.Button,{type:"button",asChild:!0,children:(0,n.jsx)(i.N_,{to:"/admin/blog/",children:"Back to all posts"})})]})]})]}):(0,n.jsxs)("div",{className:"space-y-6",children:[(0,n.jsx)(rB,{open:e8,onOpenChange:e=>{e7(e),e||(tg.current=null)},title:"Add media",confirmLabel:"Insert into post",onConfirm:rI}),(0,n.jsx)(tQ,{open:null!==to,onOpenChange:e=>{(e||!tt)&&(e||td(null))},children:(0,n.jsxs)(tX,{className:"sm:max-w-md",hideCloseButton:tt,onPointerDownOutside:e=>tt&&e.preventDefault(),onEscapeKeyDown:e=>tt&&e.preventDefault(),children:[(0,n.jsxs)(tZ,{children:[(0,n.jsx)(t1,{children:"Importing external images"}),(0,n.jsx)(t2,{className:"sr-only",children:"Progress while each hotlinked image is downloaded and saved to your media library."})]}),to?(0,n.jsxs)("div",{className:"space-y-3 py-1",children:[(0,n.jsxs)("div",{className:"flex justify-between gap-3 text-sm text-muted-foreground",children:[(0,n.jsx)("span",{children:to.currentUrl?"Image ".concat(to.completed+1," of ").concat(to.total):to.completed>=to.total?"Done":"Completed ".concat(to.completed," of ").concat(to.total)}),(0,n.jsx)("span",{className:"tabular-nums font-medium text-foreground",children:(()=>{let{completed:e,total:t,currentUrl:r}=to;if(t<=0)return"0%";let n=r?Math.min(99,Math.round((e+.4)/t*100)):Math.round(e/t*100);return"".concat(n,"%")})()})]}),(0,n.jsx)(nk,{value:to.total>0?to.currentUrl?Math.min(99,(to.completed+.4)/to.total*100):to.completed/to.total*100:0}),to.currentUrl?(0,n.jsx)("p",{className:"text-xs text-muted-foreground break-all line-clamp-2",title:to.currentUrl,children:to.currentUrl}):to.completed>0&&to.completed<to.total?(0,n.jsx)("p",{className:"text-xs text-muted-foreground",children:"Saving to storage…"}):null]}):null]})}),(0,n.jsx)(np,{open:!!tc&&rO.length>0,onOpenChange:e=>{e||tu(null)},items:rO,activeIndex:0,onRequestDelete:e=>{tu(null),th(e)},onStorageRenamed:(e,t)=>{V(r=>{let n=eV(e,t,T.N),a=r.content||"";for(let[e,t]of n)e&&t&&e!==t&&(a=a.split(e).join(t));return{...r,content:a,cover_image_url:aR(r.cover_image_url,n),og_image_url:aR(r.og_image_url,n),twitter_image_url:aR(r.twitter_image_url,n)}}),tu(t)}}),(0,n.jsx)(tQ,{open:!!ej,onOpenChange:e=>{e||ew(null)},children:(0,n.jsxs)(tX,{className:"sm:max-w-2xl max-h-[min(92vh,760px)] flex flex-col gap-0 overflow-hidden p-0",children:[(0,n.jsxs)(tZ,{className:"px-6 pt-6 pb-2 shrink-0",children:[(0,n.jsx)(t1,{children:"Review SEO fixes"}),(0,n.jsxs)(t2,{children:["Automatic steps (e.g. body ",(0,n.jsx)("code",{className:"text-xs bg-muted px-1 rounded",children:"H1"}),"→",(0,n.jsx)("code",{className:"text-xs bg-muted px-1 rounded",children:"H2"}),") plus AI adjustments for meta, alt text, etc. Internal and external links are not changed here — add those in the main content area (e.g. Add (AI) links). Apply to load into the editor — use"," ",(0,n.jsx)("strong",{className:"text-foreground",children:"Save"})," when you want this in the database."]})]}),ej?(0,n.jsxs)(t9,{value:e_,onValueChange:eN,className:"flex min-h-0 flex-1 flex-col px-6",children:[(0,n.jsxs)(t7,{className:"mb-2 w-full justify-start overflow-x-auto",children:[(0,n.jsx)(re,{value:"summary",children:"Summary"}),(0,n.jsx)(re,{value:"fields",children:"SEO fields"}),(0,n.jsx)(re,{value:"body",children:"Body HTML"})]}),(0,n.jsxs)(rt,{value:"summary",className:"mt-0 min-h-0 flex-1 overflow-y-auto max-h-[min(48vh,400px)] space-y-4 pr-1 text-sm",children:[(null==(t=ej.deterministic_steps)?void 0:t.length)?(0,n.jsxs)("div",{children:[(0,n.jsx)("p",{className:"text-xs font-medium text-muted-foreground mb-1.5",children:"Automatic"}),(0,n.jsx)("ul",{className:"list-disc space-y-1 pl-5",children:ej.deterministic_steps.map((e,t)=>(0,n.jsx)("li",{children:e},"det-".concat(t)))})]}):null,(null==(r=ej.ai_summary)?void 0:r.length)?(0,n.jsxs)("div",{children:[(0,n.jsx)("p",{className:"text-xs font-medium text-muted-foreground mb-1.5",children:"AI"}),(0,n.jsx)("ul",{className:"list-disc space-y-1 pl-5",children:ej.ai_summary.map((e,t)=>(0,n.jsx)("li",{children:e},"ai-".concat(t)))})]}):(0,n.jsx)("p",{className:"text-xs text-muted-foreground",children:"No extra AI summary lines — 
1check SEO fields / body tabs."})]}),(0,n.jsxs)(rt,{value:"fields",className:"mt-0 min-h-0 flex-1 overflow-y-auto max-h-[min(48vh,400px)] space-y-3",children:[(0,n.jsxs)("div",{className:"grid gap-1",children:[(0,n.jsx)(tH,{className:"text-xs text-muted-foreground",children:"SEO title (proposed)"}),(0,n.jsx)(rP.T,{readOnly:!0,rows:2,value:ej.seo_title,className:"resize-none font-mono text-xs"})]}),(0,n.jsxs)("div",{className:"grid gap-1",children:[(0,n.jsx)(tH,{className:"text-xs text-muted-foreground",children:"Meta description (proposed)"}),(0,n.jsx)(rP.T,{readOnly:!0,rows:5,value:ej.seo_description,className:"resize-y font-mono text-xs min-h-[5rem]"})]}),(0,n.jsxs)("div",{className:"grid gap-1",children:[(0,n.jsx)(tH,{className:"text-xs text-muted-foreground",children:"Excerpt (proposed)"}),(0,n.jsx)(rP.T,{readOnly:!0,rows:4,value:ej.excerpt,className:"resize-y font-mono text-xs min-h-[4rem]"})]})]}),(0,n.jsxs)(rt,{value:"body",className:"mt-0 min-h-0 flex-1 overflow-y-auto max-h-[min(48vh,400px)]",children:[(0,n.jsxs)("p",{className:"text-xs text-muted-foreground mb-2",children:["Length ",null!=(m=null==(l=ej.content_html)?void 0:l.length)?m:0," characters (sanitized on apply)."]}),(0,n.jsx)(rP.T,{readOnly:!0,value:ej.content_html||"",className:"min-h-[240px] font-mono text-[11px] leading-relaxed"})]})]}):null,(0,n.jsxs)(t0,{className:"border-t px-6 py-4 shrink-0 flex flex-col gap-2 sm:flex-row sm:justify-end",children:[(0,n.jsx)(L.Button,{type:"button",variant:"outline",onClick:()=>ew(null),children:"Discard"}),(0,n.jsx)(L.Button,{type:"button",onClick:function(){if(!ej)return;let e=e$.A.sanitize(ej.content_html||"");rT("seo_title",ej.seo_title),rT("seo_description",ej.seo_description),rT("excerpt",ej.excerpt),rT("content",e),ew(null),f({title:"SEO fixes applied",description:"Changes are in the editor — save the post when you are ready."})},disabled:!ej,children:"Apply to editor"})]})]})}),(0,n.jsx)(er,{open:!!tm,onOpenChange:e=>!e&&th(null),children:(0,n.jsxs)(es,{children:[(0,n.jsxs)(ei,{children:[(0,n.jsx)(eo,{children:"Delete this file?"}),(0,n.jsxs)(ed,{children:["This removes the object from Supabase Storage. Posts that still reference this URL will show a broken image unless you update them. This editor will remove the image from the current post body after deletion.",tm?(0,n.jsx)("span",{className:"mt-2 block break-all font-mono text-xs text-foreground",children:tm}):null]})]}),(0,n.jsxs)(el,{children:[(0,n.jsx)(eu,{children:"Cancel"}),(0,n.jsx)(ec,{className:"bg-destructive text-destructive-foreground hover:bg-destructive/90",onClick:()=>tm&&rR.mutate(tm),children:"Delete"})]})]})}),(0,n.jsx)(tQ,{open:e1,onOpenChange:e=>{e4(e),e||e6([])},children:(0,n.jsxs)(tX,{className:"sm:max-w-lg max-h-[min(85vh,640px)] flex flex-col gap-0 p-0",children:[(0,n.jsx)("div",{className:"p-6 pb-2 space-y-2 shrink-0",children:(0,n.jsxs)(tZ,{children:[(0,n.jsx)(t1,{children:"Suggested internal & external links"}),(0,n.jsxs)(t2,{children:["Tick the pairs you want, then ",(0,n.jsx)("strong",{className:"text-foreground",children:"Add selected"}),". Or"," ",(0,n.jsx)("strong",{className:"text-foreground",children:"Add all"}),". External rows marked “unverified” were not checked live — review before enabling."]})]})}),(0,n.jsx)("div",{className:"border-y px-6 py-3 overflow-y-auto min-h-0 max-h-[min(50vh,360px)] space-y-2",children:0===e5.length?(0,n.jsx)("p",{className:"text-sm text-muted-foreground",children:"No rows."}):e5.map(e=>{let t=function(e){let t=String(e||"").trim();if(!t)return"";if(ti(t))return e0(t);if(t.startsWith("/")&&!t.startsWith("//")){let e=eZ(t);return"".concat(eS.W6.replace(/\/$/,"")).concat(e)}return""}(e.path);return(0,n.jsxs)("div",{className:"flex gap-2 sm:gap-3 rounded-lg border bg-card/50 p-3 text-sm items-start hover:bg-muted/40",children:[(0,n.jsx)(ra,{id:"link-review-".concat(e.id),checked:e.selected,onCheckedChange:t=>e6(r=>r.map(r=>r.id===e.id?{...r,selected:!!t}:r)),className:"mt-0.5 shrink-0"}),(0,n.jsxs)("label",{htmlFor:"link-review-".concat(e.id),className:"min-w-0 flex-1 space-y-1 cursor-pointer",children:[(0,n.jsxs)("span",{className:"flex flex-wrap items-center gap-2",children:[(0,n.jsxs)("span",{className:"font-medium text-foreground break-words",children:["“",e.anchorText,"”"]}),"external"===e.kind?(0,n.jsx)("span",{className:"text-[10px] uppercase tracking-wide px-1.5 py-0.5 rounded bg-muted text-muted-foreground",children:"Exter
1nal"}):(0,n.jsx)("span",{className:"text-[10px] uppercase tracking-wide px-1.5 py-0.5 rounded bg-muted text-muted-foreground",children:"Internal"}),"external"===e.kind&&"unknown"===e.verifyStatus?(0,n.jsx)("span",{className:"text-[10px] text-amber-700 dark:text-amber-300",children:"Unverified"}):null]}),(0,n.jsx)("span",{className:"text-xs text-muted-foreground font-mono break-all",children:e.path})]}),(0,n.jsx)(L.Button,{type:"button",variant:"outline",size:"icon",className:"shrink-0 h-8 w-8",disabled:!t,title:t?"Open link in new tab":"No URL to open","aria-label":"Open link in new tab",onClick:e=>{e.preventDefault(),e.stopPropagation(),t&&window.open(t,"_blank","noopener,noreferrer")},children:(0,n.jsx)(rK.A,{className:"h-4 w-4"})})]},e.id)})}),(0,n.jsxs)("div",{className:"p-6 pt-4 flex flex-col gap-2 sm:flex-row sm:flex-wrap sm:justify-between shrink-0",children:[(0,n.jsxs)("div",{className:"flex gap-2 flex-wrap",children:[(0,n.jsx)(L.Button,{type:"button",variant:"outline",size:"sm",onClick:()=>e6(e=>e.map(e=>({...e,selected:!0}))),children:"Select all"}),(0,n.jsx)(L.Button,{type:"button",variant:"destructiveOutline",size:"sm",onClick:()=>e6(e=>e.map(e=>({...e,selected:!1}))),children:"Clear ticks"})]}),(0,n.jsxs)(t0,{className:"flex flex-col sm:flex-row gap-2 w-full sm:w-auto sm:justify-end",children:[(0,n.jsx)(L.Button,{type:"button",variant:"secondary",onClick:function(){let e=r6(no().provider),t=e5.filter(e=>e.selected).map(e=>({path:e.path,anchorText:e.anchorText}));if(!t.length)return void f({title:"Nothing selected",description:"Tick the rows you want, or use Add all."});r3(t,e),e4(!1),e6([])},children:"Add selected"}),(0,n.jsx)(L.Button,{type:"button",onClick:function(){let e=r6(no().provider);r3(e5.map(e=>({path:e.path,anchorText:e.anchorText})),e),e4(!1),e6([])},children:"Add all"})]})]})]})}),(0,n.jsx)(tQ,{open:ek,onOpenChange:e=>{eA(e),e||(eL(""),eG(null),tv.current=null,eR(!1))},children:(0,n.jsxs)(tX,{className:eD?"sm:max-w-2xl max-h-[90vh] flex flex-col":"sm:max-w-lg",children:[(0,n.jsxs)(tZ,{children:[(0,n.jsx)(t1,{children:"Content wizard"}),(0,n.jsxs)(t2,{children:["Transforms ",(0,n.jsx)("strong",{className:"text-foreground",children:"only the text you highlighted"})," before opening this dialog (saves API tokens). The model result is shown for review before anything is written to the editor. Same provider as Internal & external links in"," ",(0,n.jsx)(i.N_,{to:"/admin/api-settings/",className:"text-primary hover:underline",children:"API Settings"}),"."]})]}),eD?(0,n.jsxs)("div",{className:"flex min-h-0 flex-1 flex-col gap-3 py-2",children:[(0,n.jsxs)("div",{className:"grid gap-2",children:[(0,n.jsx)(tH,{children:"Preview (sanitized)"}),(0,n.jsx)("div",{className:"content-wizard-preview-html blog-quill-body prose prose-slate max-w-none max-h-[min(50vh,420px)] overflow-auto rounded-md border border-border bg-background p-4 text-sm leading-relaxed text-foreground",dangerouslySetInnerHTML:{__html:eD}})]}),(0,n.jsx)("p",{className:"text-xs text-muted-foreground",children:"Original selection stays in the editor until you click Replace in editor. Close the dialog and run the wizard again to try a different action."})]}):(0,n.jsxs)("div",{className:"space-y-4 py-2",children:[(0,n.jsxs)("div",{className:"grid gap-2",children:[(0,n.jsx)(tH,{htmlFor:"content_wizard_mode",children:"Action"}),(0,n.jsxs)(rl,{value:eq,onValueChange:e=>eM(e),children:[(0,n.jsx)(rd,{id:"content_wizard_mode",children:(0,n.jsx)(ro,{placeholder:"Choose action"})}),(0,n.jsxs)(rm,{children:[(0,n.jsx)(rh,{value:"format_professional",children:"Professional structure (H2–H4, lists, spacing)"}),(0,n.jsx)(rh,{value:"shorten",children:"Shorten (~25–40%)"}),(0,n.jsx)(rh,{value:"expand",children:"Expand with detail (~30–50%)"}),(0,n.jsx)(rh,{value:"custom",children:"Custom instructions…"})]})]})]}),"custom"===eq?(0,n.jsxs)("div",{className:"grid gap-2",children:[(0,n.jsx)(tH,{htmlFor:"content_wizard_custom",children:"Your instructions"}),(0,n.jsx)(rP.T,{id:"content_wizard_custom",value:eP,onChange:e=>eL(e.target.value),rows:5,placeholder:"e.g. Turn the middle section into bullet takeaways; keep all images and links.",className:"resize-y min-h-[100px] font-sans text-sm"})]}):null]}
1),(0,n.jsx)(t0,{className:"flex-col gap-2 sm:flex-row sm:justify-end shrink-0",children:eD?(0,n.jsxs)(n.Fragment,{children:[(0,n.jsxs)(L.Button,{type:"button",variant:"outline",className:"gap-1.5",onClick:()=>void ne(),disabled:eE,children:[(0,n.jsx)(rH.A,{className:"h-4 w-4","aria-hidden":!0}),"Copy"]}),(0,n.jsx)(L.Button,{type:"button",variant:"outline",onClick:()=>eA(!1),disabled:eE,children:"Cancel"}),(0,n.jsx)(L.Button,{type:"button",onClick:function(){if(!(null==eD?void 0:eD.trim()))return void f({title:"Nothing to apply",description:"Generate a preview first.",variant:"destructive"});let e=tv.current;if(!e)return void f({title:"Selection expired",description:"Close the wizard, select the passage again, and run the wizard once more.",variant:"destructive"});let{provider:t}=no();try{if("quill"===e.kind){let t=tx.current;if(!t)return void f({title:"Visual editor not ready",description:"Switch to Visual and try again.",variant:"destructive"});t.deleteText(e.index,e.length,"user"),t.clipboard.dangerouslyPasteHTML(e.index,eD,"user")}else{let t=H.content||"";rT("content","".concat(t.slice(0,e.start)).concat(eD).concat(t.slice(e.end)))}tv.current=null,eR(!1),eG(null),eA(!1),f({title:"Selection updated",description:"".concat(r6(t)," — your highlighted portion was replaced. Review in Visual or Code view.")})}catch(e){f({title:"Could not replace selection",description:(null==e?void 0:e.message)||String(e),variant:"destructive"})}},disabled:eE,children:"Replace in editor"})]}):(0,n.jsxs)(n.Fragment,{children:[(0,n.jsx)(L.Button,{type:"button",variant:"outline",onClick:()=>eA(!1),disabled:eE,children:"Cancel"}),(0,n.jsx)(L.Button,{type:"button",onClick:()=>void r7(),disabled:eE||!tG||!eO,children:eE?"Working…":"Generate preview"})]})})]})}),(0,n.jsxs)("div",{className:"flex items-start justify-between gap-4",children:[(0,n.jsxs)("div",{className:"min-w-0",children:[(0,n.jsxs)("p",{className:"text-sm text-muted-foreground",children:[(0,n.jsx)(i.N_,{to:"/admin/blog/",className:"hover:underline",children:"Blog"})," ","/ ",x?"New post":"Edit post"]}),(0,n.jsxs)("div",{className:"flex min-w-0 items-center gap-2",children:[(0,n.jsx)("h1",{className:"text-2xl font-semibold min-w-0 flex-1 truncate",children:H.title||(x?"New post":"Untitled")}),(0,n.jsx)(tB,{variant:"secondary",className:rZ.className,"aria-label":"Status: ".concat(rZ.label),children:rZ.label})]}),rN?(0,n.jsxs)("div",{className:"flex items-center gap-1 min-w-0 max-w-full",children:[(0,n.jsx)("p",{className:"text-xs text-muted-foreground truncate min-w-0",children:rN}),(0,n.jsx)(L.Button,{type:"button",variant:"ghost",size:"icon",className:"h-7 w-7 shrink-0 text-muted-foreground hover:text-foreground",asChild:!0,children:(0,n.jsxs)("a",{href:rN,target:"_blank",rel:"noopener noreferrer",title:rX.isLive?"View live post on site":rX.isScheduled?"Open post URL (scheduled — not public until publish time)":"Open post URL on site (draft — page may not be public yet)",children:[(0,n.jsx)(rK.A,{className:"h-4 w-4","aria-hidden":!0}),(0,n.jsx)("span",{className:"sr-only",children:"View post on site"})]})})]}):null]}),(0,n.jsxs)("div",{className:"flex items-center gap-2",children:[!x&&rk?(0,n.jsx)(L.Button,{type:"button",variant:"outline",asChild:!0,children:(0,n.jsxs)("a",{href:rk,target:"_blank",rel:"noreferrer",children:["Preview",(0,n.jsx)(rK.A,{className:"w-4 h-4 ml-2"})]})}):null,x?null:(0,n.jsx)(L.Button,{type:"button",variant:"outline",onClick:()=>rE.mutate(!rX.hasDate),disabled:rE.isPending,children:rX.hasDate?"Unpublish":"Publish now"}),(0,n.jsx)(L.Button,{type:"button",onClick:r5,disabled:rC.isPending,children:rC.isPending?"Saving…":"Save"})]})]}),C?(0,n.jsx)("div",{className:"rounded-lg border border-destructive/30 bg-destructive/10 px-3 py-2 text-sm text-destructive",children:C.message}):null,S&&!x?(0,n.jsx)("div",{className:"text-sm text-muted-foreground",children:"Loading…"}):null,(0,n.jsxs)(t9,{value:tj,onValueChange:tw,className:"w-full",children:[(0,n.jsxs)(t7,{children:[(0,n.jsx)(re,{value:"content",children:"Content"}),(0,n.jsx)(re,{value:"seo",children:"SEO"}),(0,n.jsx)(re,{value:"social",children:"Social"}),(0,n.jsx)(re,{value:"advanced",children:"Advanced"})]}),(0,n.jsx)(rt,{value:"content",className:"mt-2",children:(0,n.jsxs)("div",{className:"grid lg:grid-cols-[1fr_360px] gap-6",children:[(0,n.jsxs)("div",{className:"space-y-4 rounded-2xl border bg-card p-5",children:[(0,n.jsxs)("div",{className:"grid gap-2",children:[(0,n.jsx)(tH,{htmlFor:"title",children:"Title"}),(0,n.jsx)(tR.p,{id:"title",value:H.title,onChange:e=>rT("title",e.target.value),placeholder:"e.g. How to choose fabrics for your first collection"})]}),(0,n.jsxs)("div",{className:"grid gap-2",children:[(0,n.jsx)(tH,{htmlFor:"slug",children:"Slug"}),(0,n.jsxs)("div",{className:(0,b.cn)("flex min-h-9 w-full overflow-hidden rounded-md border border-input bg-background shadow-sm transition-colors","focus-within:ring-1 focus-within:ring-ring"),children:[(0,n.jsx)(tR.p,{id:"slug",value:H.slug,readOnly:!t_,"aria-readonly":!t_,onChange:e=>rT("slug",e.target.value),onKeyDown:e=>{t_&&"Escape"===e.key&&rQ()},placeholder:"url-friendly-name (auto from title or type manually)",className:(0,b.cn)("min-w-0 flex-1 border-0 shadow-none focus-visible:ring-0 focus-visible:ring-offset-0 rounded-none h-9 px-3",!t_&&"bg-muted/40 cursor-default")}
1),(0,n.jsx)("div",{className:"flex shrink-0 items-stretch divide-x divide-border border-l border-border bg-muted/25",children:t_?(0,n.jsxs)(n.Fragment,{children:[(0,n.jsx)(L.Button,{type:"button",variant:"ghost",size:"sm",className:"h-auto min-h-9 rounded-none px-3 text-xs font-semibold text-primary hover:bg-primary/10 hover:text-primary",onClick:rY,children:"Done"}),(0,n.jsx)(L.Button,{type:"button",variant:"ghost",size:"sm",className:"h-auto min-h-9 rounded-none px-3 text-xs font-medium",onClick:rQ,children:"Cancel"})]}):(0,n.jsxs)(n.Fragment,{children:[(0,n.jsx)(L.Button,{type:"button",variant:"ghost",size:"sm",className:"h-auto min-h-9 rounded-none px-3 text-xs font-semibold whitespace-nowrap",onClick:rG,children:"Edit slug"}),(0,n.jsx)(L.Button,{type:"button",variant:"ghost",size:"sm",className:"h-auto min-h-9 rounded-none px-3 text-xs font-medium whitespace-nowrap",onClick:function(){H.title&&rT("slug",ab(H.title))},title:"Generate slug from the post title",children:"Auto slug"})]})})]}),t_?(0,n.jsx)("p",{className:"text-xs text-muted-foreground",children:"Press Esc to cancel. Slug is normalized on save; use letters, numbers, and hyphens."}):null]}),(0,n.jsxs)("div",{className:"grid gap-2",children:[(0,n.jsx)(tH,{id:"blog-content-label",children:"Content"}),(0,n.jsxs)("div",{className:"rounded-xl border bg-background min-h-[400px] flex flex-col","aria-labelledby":"blog-content-label",children:[(0,n.jsx)("div",{className:"sticky top-0 z-40 border-b border-border bg-background/95 shadow-sm backdrop-blur supports-[backdrop-filter]:bg-background/90",children:(0,n.jsxs)("div",{className:"not-prose",children:[(0,n.jsxs)("div",{className:"flex min-w-0 flex-wrap items-end justify-between gap-2 bg-muted/40 px-2 pt-1 pb-1.5",children:[(0,n.jsxs)("div",{className:"flex shrink-0 gap-0",role:"tablist","aria-label":"Editor view",children:[(0,n.jsx)("button",{type:"button",role:"tab","aria-selected":"visual"===ty,onClick:()=>tb("visual"),className:(0,b.cn)("px-3 py-2 text-sm font-medium rounded-md border border-transparent transition-colors","visual"===ty?"bg-background text-primary border-border shadow-sm z-10":"text-muted-foreground hover:text-foreground hover:bg-muted/60"),children:"Visual"}),(0,n.jsx)("button",{type:"button",role:"tab","aria-selected":"code"===ty,onClick:()=>tb("code"),className:(0,b.cn)("px-3 py-2 text-sm font-medium rounded-md border border-transparent transition-colors","code"===ty?"bg-background text-primary border-border shadow-sm z-10":"text-muted-foreground hover:text-foreground hover:bg-muted/60"),children:"Code"})]}),(0,n.jsxs)("div",{className:"flex shrink-0 flex-wrap items-center justify-end gap-2",children:[(0,n.jsxs)(L.Button,{type:"button",variant:"outline",size:"sm",className:"shrink-0 gap-1.5 h-9",disabled:eE||!tG||!tW,onClick:function(){if(!tG)return void f({title:"AI not configured",description:"In Admin → API Settings, pick the provider under “Internal & external links” and add at least one API key."});if(!tW)return void f({title:"Add body content first",description:"Write some article text, then highlight the part you want to transform."});let e="visual"===ty?function(e){if(!e)return null;let t=e.getSelection(!0);if(!t||0===t.length)return null;e.focus(),e.setSelection(t.index,t.length,"silent");let r=window.getSelection();if(!r||0===r.rangeCount)return null;let n=r.getRangeAt(0);if(!e.root.contains(n.commonAncestorContainer)||n.collapsed)return null;let a=n.cloneContents(),s=document.createElement("div");s.appendChild(a);let i=s.innerHTML.trim();return i?{kind:"quill",index:t.index,length:t.length,html:i}:null}(tx.current):function(e){if(!e)return null;let t=e.selectionStart,r=e.selectionEnd;return null==t||null==r||t===r?null:{kind:"code",start:t,end:r,html:e.value.slice(t,r)}}(tf.current);return e?a_(e.html).replace(/\s+/g," ").trim().length<12?void f({title:"Selection too short",description:"Select a bit more text (at least ".concat(12," characters of real content).")}):void(tv.current=e,eR(!0),eA(!0)):void f({title:"Select text first",description:"In Visual or Code view, highlight the paragraph(s) or section to change, then click Content wizard. Only the selection is sent to the API (saves tokens)."})},title:tW?tG?"Select text in the editor, then open — only the selection is sent (".concat(r6(tK.provider),")"):"Configure API Settings — Internal & external links":"Add body content first",children:[(0,n.jsx)(rV.A,{className:"h-3.5 w-3.5 ".concat(eE?"animate-pulse":""),"aria-hidden":!0}),"Content wizard"]}),(0,n.jsxs)(L.Button,{type:"button",variant:"outline",size:"sm",className:"shrink-0 gap-1.5 h-9",disabled:tt||!String(H.content||"").trim(),onClick:()=>void rz(),title:"Hotlinked images from other sites are downloaded (when allowed), saved to your Media Library, and replaced in this post so you are not depending on external URLs.",children:[(0,n.jsx)(ap.A,{className:"h-3.5 w-3.5 ".concat(tt?"animate-pulse":""),"aria-hidden":!0}),"Import external images"]})]})]}
1),"visual"===ty?(0,n.jsx)("div",{id:N,className:"admin-quill-toolbar-slot border-t border-border/70 bg-background min-w-0"}):null]})}),"visual"===ty?(0,n.jsx)(ah,{value:H.content,onChange:e=>rT("content",e),modules:rJ,toolbarMountId:N,toolbarGroups:aL,onRequestImage:rM,onRequestInlineImageEdit:rD,onClipboardImageUploaded:rU,onQuillReady:e=>{tx.current=e},className:"flex-1 flex flex-col min-h-0 [&_.ql-container]:border-0 [&_.ql-container]:border-t [&_.ql-container]:flex-1 [&_.ql-container]:overflow-hidden [&_.ql-container]:rounded-b-xl [&_.ql-editor]:min-h-[350px]"}):(0,n.jsx)(rP.T,{ref:tf,value:H.content,onChange:e=>rT("content",e.target.value),spellCheck:!1,className:"min-h-[400px] rounded-b-xl border-0 focus-visible:ring-0 focus-visible:ring-offset-0 font-mono text-[13px] leading-relaxed resize-y bg-background","aria-label":"HTML source"})]}),(0,n.jsxs)("p",{className:"text-xs text-muted-foreground",children:[r$.words.toLocaleString()," words \xb7 ",r$.readTime]}),(0,n.jsxs)("div",{className:"mt-5 rounded-2xl border border-border bg-card p-6 shadow-sm space-y-4",children:[(0,n.jsxs)("div",{className:"flex items-center justify-between gap-2 flex-wrap",children:[(0,n.jsx)("h3",{className:"font-semibold text-foreground",children:"Internal & external links"}),(0,n.jsx)(i.N_,{to:"/admin/auto-linking/",className:"text-xs text-primary font-medium hover:underline shrink-0",children:"Internal link sitemap"})]}),(0,n.jsx)("p",{className:"text-xs text-muted-foreground",children:"Analyze lists existing anchors. Add (AI) requests suggestions from your default model, then inserts links using the internal URL allowlist and your quotas."}),Q>0&&!tV?(0,n.jsxs)("p",{className:"text-xs font-medium text-amber-900 dark:text-amber-100 bg-amber-100 dark:bg-amber-950/60 border border-amber-300/90 dark:border-amber-700 rounded-lg px-3 py-2.5",children:["Add (AI) internal links need a sitemap —"," ",(0,n.jsx)(i.N_,{to:"/admin/auto-linking/",className:"underline font-semibold",children:"Internal link sitemap"}),". Or set max internal to 0 for external-only."]}):null,(0,n.jsxs)("div",{className:"flex flex-wrap items-end gap-4",children:[(0,n.jsxs)("div",{className:"space-y-1",children:[(0,n.jsx)("label",{htmlFor:"internal_link_max",className:"text-xs text-muted-foreground",children:"Max internal"}),(0,n.jsx)(tR.p,{id:"internal_link_max",type:"number",min:0,max:20,className:"h-10 w-20 bg-background border border-border rounded-lg px-3 py-1.5 text-sm font-semibold tabular-nums",value:Q,onChange:e=>{let t=Math.min(20,Math.max(0,Number(e.target.value)||0));Y(t),rb(t,J)}})]}),(0,n.jsxs)("div",{className:"space-y-1",children:[(0,n.jsx)("label",{htmlFor:"external_link_max",className:"text-xs text-muted-foreground",children:"Max external"}),(0,n.jsx)(tR.p,{id:"external_link_max",type:"number",min:0,max:20,className:"h-10 w-20 bg-background border border-border rounded-lg px-3 py-1.5 text-sm font-semibold tabular-nums",value:J,onChange:e=>{let t=Math.min(20,Math.max(0,Number(e.target.value)||0));$(t),rb(Q,t)}})]}),(0,n.jsx)("button",{type:"button",disabled:ee||X||!!em,onClick:()=>void tJ(rv.current.content||""),className:"flex items-center gap-1.5 px-4 py-2 bg-orange-500 hover:bg-orange-600 disabled:opacity-60 text-white text-sm font-semibold rounded-lg transition-colors",title:"List links in the body and verify external URLs",children:ee||em&&!X?(0,n.jsxs)(n.Fragment,{children:[(0,n.jsx)(rg.A,{className:"w-3.5 h-3.5 animate-spin shrink-0"}),(null==em?void 0:em.phase)==="verify"?"Verifying ".concat(null!=(h=em.completed)?h:0,"/").concat(null!=(p=em.total)?p:"?"):(null==em?void 0:em.phase)==="packaging"?"Packaging…":"Analyzing…"]}):"Analyze"}),(0,n.jsxs)("button",{type:"button",disabled:X||ee||!tY,onClick:()=>void r8(),className:"flex items-center gap-1.5 px-4 py-2 text-sm font-semibold text-primary bg-primary/10 rounded-lg hover:bg-primary/20 transition-colors disabled:opacity-50 border border-primary/30",title:tG?Q>0&&!tV?"No sitemap — add one under Internal link sitemap, or set max internal to 0":Q+J<1?"Increase max internal or external":"".concat(r6(tK.provider)," — suggest links"):"Configure API Settings first",children:[X?(0,n.jsx)(rg.A,{className:"w-3.5 h-3.5 animate-spin shrink-0"}):(0,n.jsx)(ag.A,{className:"w-3.5 h-3.5 shrink-0"}),"Add (AI)"]})]}),X||ee?(0,n.jsxs)("div",{className:"space-y-2 pt-2 border-t border-border/80",role:"status","aria-live":"polite","aria-busy":"true",children:[(0,n.jsx)("p",{className:"text-xs text-muted-foreground",children:X?em?"ai"===em.phase?"Asking the AI for internal and external link suggestions — this can take a little while.":"packaging"===em.phase?"Preparing the suggestion list…":em.total>0?"Checking external URLs (".concat(em.completed,"/").concat(em.total,")…"):"Checking external URLs…":"Starting…":em?"verify"===em.phase&&em.total>0?"Checking external URLs (".concat(em.completed,"/").concat(em.total,")…"):"packaging"===em.phase?"Packaging…":"Analyzing…":"Starting…"}),(null==em?void 0:em.phase)==="verify"&&em.total>0?(0,n.jsx)(nk,{value:Math.min(100,em.completed/Math.max(1,em.total)*100),className:"h-2"}):X?(0,n.jsx)("div",{className:"h-2 w-full overflow-hidden rounded-full bg-primary/20","aria-hidden":!0,
1children:(0,n.jsx)("div",{className:"h-full w-[38%] max-w-[min(12rem,100%)] rounded-full bg-primary/65 motion-safe:animate-pulse"})}):null]}):null,(0,n.jsxs)("div",{className:"pt-4 border-t border-border",children:[(0,n.jsx)("h4",{className:"text-xs font-bold text-foreground mb-2",children:"Links in body"}),0===en.length?(0,n.jsx)("p",{className:"text-xs text-muted-foreground",children:"No links detected yet — click Analyze or add links in the editor."}):(0,n.jsx)("ul",{className:"text-xs space-y-1.5 max-h-40 overflow-y-auto",children:en.map((e,t)=>(0,n.jsxs)("li",{className:"flex flex-col sm:flex-row sm:items-center gap-1 border-b border-border/60 pb-1",children:[(0,n.jsx)("span",{className:"external"===e.kind?"text-orange-600 dark:text-orange-400 font-bold shrink-0":"text-primary font-bold shrink-0",children:"external"===e.kind?"External":"Internal"}),"bad"===e.reachability?(0,n.jsx)("span",{className:"text-[9px] font-bold px-1.5 py-0.5 rounded bg-destructive/15 text-destructive shrink-0",children:"404"}):null,"ok"===e.reachability?(0,n.jsx)("span",{className:"text-[9px] font-bold px-1.5 py-0.5 rounded bg-green-500/15 text-green-600 dark:text-green-400 shrink-0",children:"OK"}):null,(0,n.jsx)("span",{className:"text-muted-foreground truncate font-mono flex-1 min-w-0",children:e.href}),e.text?(0,n.jsxs)("span",{className:"text-foreground/80 truncate sm:ml-2",children:['"',e.text,'"']}):null,(0,n.jsx)("button",{type:"button",onClick:()=>(function(e){let t=function(e,t){let r,n=String(null!=e?e:"");if(!n.trim()||!Number.isFinite(t)||t<0)return n;try{r=new DOMParser().parseFromString(n,"text/html")}catch(e){return n}let a=[...r.querySelectorAll("a[href]")].filter(e=>ng(e.getAttribute("href")));if(t>=a.length)return n;let s=a[t],i=s.parentNode;if(!i)return n;for(;s.firstChild;)i.insertBefore(s.firstChild,s);return i.removeChild(s),r.body?r.body.innerHTML:n}(H.content||"",e);rT("content",t),ea(nf(nx(t)))})(e.removeIndex),title:"Remove this link",className:"shrink-0 text-destructive hover:text-destructive/80 transition-colors px-1 sm:ml-auto","aria-label":"Remove link: ".concat(e.text||e.href),children:(0,n.jsx)(rW.A,{className:"w-3.5 h-3.5"})})]},"".concat(e.href,"-").concat(e.removeIndex,"-").concat(t)))})]})]})]}),(0,n.jsx)("div",{className:"grid gap-2",children:(0,n.jsxs)("div",{className:"relative rounded-md border border-input bg-background shadow-sm focus-within:ring-2 focus-within:ring-ring focus-within:ring-offset-2 ring-offset-background",children:[(0,n.jsxs)("div",{className:"flex items-center justify-between gap-2 border-b border-border px-3 py-1.5",children:[(0,n.jsx)(tH,{htmlFor:"excerpt",className:"text-sm font-medium leading-none",children:"Excerpt"}),(0,n.jsx)(L.Button,{type:"button",variant:"ghost",size:"icon",className:"h-8 w-8 shrink-0 text-muted-foreground hover:text-foreground",disabled:eg||!tG||!tW,onClick:()=>void r9(),title:tW?tG?"Generate excerpt with ".concat(r6(tK.provider)," — same provider as Add (AI) links (≤150 characters)"):"Configure API Settings: choose provider under Internal & external links and add its key(s)":"Add body content first — the excerpt is generated from the article text","aria-label":tW?tG?"Generate excerpt with ".concat(r6(tK.provider)):"Generate excerpt with AI — configure API Settings first":"Generate excerpt with AI — add body content first",children:(0,n.jsx)(ag.A,{className:"h-4 w-4 ".concat(eg?"animate-pulse":"")})})]}),(0,n.jsx)(rP.T,{id:"excerpt",value:H.excerpt,onChange:e=>rT("excerpt",e.target.value),rows:4,className:"border-0 rounded-t-none rounded-b-md focus-visible:ring-0 focus-visible:ring-offset-0 shadow-none resize-y min-h-[5.5rem]"})]})})]}),(0,n.jsxs)("div",{className:"space-y-4",children:[(0,n.jsxs)("div",{className:"rounded-2xl border bg-card p-5 space-y-2",children:[(0,n.jsx)("p",{className:"text-sm font-medium",children:"Status"}),x?(0,n.jsx)("p",{className:"text-xs text-muted-foreground",children:(null==(d=H.scheduled_at)?void 0:d.trim())?"Date is set — Save sends it to the database.":"New draft — Save when you are ready."}):(0,n.jsx)("p",{className:"text-xs text-muted-foreground",children:rX.isScheduled?"Scheduled \xb7 ".concat(aN(null==k?void 0:k.published_at)):rX.isLive?"Last Update at ".concat(aN(null==k?void 0:k.published_at)):"Draft — not on the public blog yet."}),(0,n.jsxs)("div",{className:"pt-2 grid gap-2",children:[(0,n.jsx)(tH,{htmlFor:"scheduled_at",children:"Publish date & time"}),(0,n.jsxs)("div",{className:"flex flex-wrap items-center gap-2",children:[(0,n.jsx)(tR.p,{id:"scheduled_at",type:"datetime-local",value:H.scheduled_at,onChange:e=>rT("scheduled_at",e.target.value),className:"min-w-0 flex-1 basis-[12rem] pl-9 pr-3 admin-datetime-local-input"}),x?null:(0,n.jsx)(L.Button,{type:"button",variant:"destructive",size:"sm",className:"shrink-0",onClick:()=>rT("scheduled_at",""),children:"Clear date"})]})]}),(0,n.jsxs)("div",{className:"pt-2 border-t space-y-2",children:[(0,n.jsx)("p",{className:"text-[11px] font-medium text-muted-foreground",children:"Last saved"}),(0,n.jsx)("div",{className:"flex flex-col gap-2",children:(0,n.jsxs)("div",{className:"flex items-center gap-2 text-xs min-w-0",title:"Database — autosaves about ".concat(.8,"s after you stop typing, or when you click Save."),children:[(0,n.jsx)(ax.A,{className:"h-4 w-4 shrink-0 text-muted-foreground","aria-hidden":!0}),(0,n.jsx)("span",{className:"text-muted-foreground shrink-0",children:"Cloud"}),(0,n.jsx)("span",{className:"ml-auto tabular-nums text-foreground font-medium truncate",children:ru?ru.toLocaleStr
1ing(void 0,{month:"short",day:"numeric",hour:"numeric",minute:"2-digit"}):"—"})]})})]})]}),(0,n.jsx)("div",{className:"rounded-2xl border bg-card p-5",children:(0,n.jsx)(rF,{label:"Cover image",value:H.cover_image_url,onChange:e=>rT("cover_image_url",e),useMediaPicker:!0,mediaPickerTitle:"Cover image",mediaPickerConfirmLabel:"Use as cover image",maxWidth:2560,maxHeight:2560,quality:.92,onEditAttachment:e=>rD({src:e})})}),(0,n.jsxs)("div",{className:"rounded-2xl border bg-card p-5 space-y-2",children:[(0,n.jsxs)("div",{className:"flex items-center justify-between gap-2",children:[(0,n.jsx)(tH,{htmlFor:"category-select",children:"Category"}),(0,n.jsx)(i.N_,{to:"/admin/blog/categories/",className:"text-xs text-primary hover:underline shrink-0",children:"Manage"})]}),(0,n.jsxs)(rl,{value:t$,onValueChange:e=>{if("__add_new__"===e){tI(""),tA(!0);return}"__none__"===e?rT("category",""):rT("category",e)},children:[(0,n.jsx)(rd,{id:"category-select",className:"w-full",children:(0,n.jsx)(ro,{placeholder:"Choose a category"})}),(0,n.jsxs)(rm,{position:"popper",className:"max-h-72",children:[(0,n.jsx)(rh,{value:"__none__",children:"— None —"}),F.map(e=>(0,n.jsx)(rh,{value:e,children:e},e)),(null==(c=H.category)?void 0:c.trim())&&!F.includes(H.category.trim())?(0,n.jsx)(rh,{value:H.category.trim(),children:H.category.trim()}):null,(0,n.jsx)(rp,{}),(0,n.jsx)(rh,{value:"__add_new__",className:"text-primary focus:text-primary font-medium cursor-pointer",children:(0,n.jsxs)("span",{className:"flex items-center gap-2",children:[(0,n.jsx)(af.A,{className:"h-4 w-4 shrink-0 opacity-80","aria-hidden":!0}),"Add new category…"]})})]})]}),0===F.length?(0,n.jsxs)("p",{className:"text-xs text-muted-foreground",children:["Use ",(0,n.jsx)("span",{className:"font-medium text-foreground",children:"Add new category…"})," above or add under"," ",(0,n.jsx)(i.N_,{to:"/admin/blog/categories/",className:"text-primary hover:underline",children:"Blog → Categories"}),"."]}):null,(0,n.jsx)(tQ,{open:tC,onOpenChange:e=>{tA(e),e||tI("")},children:(0,n.jsxs)(tX,{className:"sm:max-w-md",children:[(0,n.jsxs)(tZ,{children:[(0,n.jsx)(t1,{children:"Add new category"}),(0,n.jsxs)(t2,{children:["Saves to your category list (same as"," ",(0,n.jsx)(i.N_,{to:"/admin/blog/categories/",className:"text-primary hover:underline",children:"Blog → Categories"}),") and selects it for this post."]})]}),(0,n.jsxs)("div",{className:"grid gap-2 py-1",children:[(0,n.jsx)(tH,{htmlFor:"new_category_name",children:"Category name"}),(0,n.jsx)(tR.p,{id:"new_category_name",value:tM,onChange:e=>tI(e.target.value),placeholder:"e.g. Sustainability",disabled:rq.isPending,onKeyDown:e=>{"Enter"===e.key&&tM.trim()&&!rq.isPending&&(e.preventDefault(),rq.mutate(tM))}})]}),(0,n.jsxs)(t0,{className:"gap-2 sm:gap-0",children:[(0,n.jsx)(L.Button,{type:"button",variant:"outline",onClick:()=>tA(!1),disabled:rq.isPending,children:"Cancel"}),(0,n.jsx)(L.Button,{type:"button",disabled:rq.isPending||!tM.trim(),onClick:()=>rq.mutate(tM),children:rq.isPending?"Adding…":"Add category"})]})]})})]}),(0,n.jsxs)("div",{className:"rounded-2xl border bg-card px-4 py-3 flex items-center justify-between gap-3",children:[(0,n.jsxs)("div",{className:"min-w-0",children:[(0,n.jsx)("p",{className:"text-sm font-medium",children:"Featured"}),(0,n.jsx)("p",{className:"text-xs text-muted-foreground",children:"Show on blog homepage featured slot"})]}),(0,n.jsx)(rL,{checked:!!H.featured,onCheckedChange:e=>rT("featured",e)})]}),(0,n.jsxs)("div",{className:"rounded-2xl border bg-card p-5 space-y-2",children:[(0,n.jsx)(tH,{htmlFor:"author-select",children:"Author"}),(0,n.jsxs)(rl,{value:t4,onValueChange:e=>rT("created_by","__none__"===e?"":e),children:[(0,n.jsx)(rd,{id:"author-select",className:"w-full",children:(0,n.jsx)(ro,{placeholder:"Select author"})}),(0,n.jsxs)(rm,{position:"popper",className:"max-h-72",children:[(0,n.jsx)(rh,{value:"__none__",children:"— Unassigned —"}),U.map(e=>(0,n.jsx)(rh,{value:e.id,title:e.email||void 0,children:aP(e)},e.id)),(null==(u=H.created_by)?void 0:u.trim())&&!U.some(e=>e.id===H.created_by.trim())?(0,n.jsx)(rh,{value:H.created_by.trim(),children:"Previous author (not in list)"}):null]})]}),(0,n.jsx)("p",{className:"text-xs text-muted-foreground",children:"Defaults to you on new posts. Change before save to publish under another admin."})]})]})]})}),(0,n.jsx)(rt,{value:"seo",className:"mt-4",children:(0,n.jsxs)("div",{className:"grid lg:grid-cols-[1fr_360px] gap-6",children:[(0,n.jsxs)("div",{className:"space-y-4 min-w-0",children:[(0,n.jsxs)("div",{className:"rounded-2xl border bg-card p-5 space-y-4",children:[(0,n.jsxs)("div",{className:"flex items-center justify-between gap-2 border-b border-border pb-3",children:[(0,n.jsxs)("div",{className:"min-w-0",children:[(0,n.jsx)("p",{className:"text-sm font-medium",children:"Basic SEO"}),(0,n.jsxs)("p",{className:"text-xs text-muted-foreground mt-0.5",children:["AI uses Google-oriented lengths: title ≤",tp.seoTitleMax," chars, meta description ≤",tp.metaDescriptionMax," (key info in first ~120 for mobile)."]})]}),(0,n.jsxs)(L.Button,{type:"button",variant:"outline",size:"sm",className:"shrink-0 gap-2",disabled:ef||!tG||!tW,onClick:()=>void nt(),title:tW?tG?"Fill SEO fields with ".concat(r6(tK.provider)):"Configure API Settings first":"Add body content first",children:[(0,n.jsx)(ag.A,{className:"h-4 w-4 ".concat(ef?"animate-pulse":"")}),ef?"Generating…":"AI fill"]})]}),(0,n.jsxs)("div",{className:"grid gap-2",children:[(0,n.jsx)(tH,{htmlFor:"seo_title",children:"SEO title"}),(0,n.jsx)(tR.p,{id:"seo_title",value:H.seo_title,onChange:e=>rT("seo_title",e.target.value)}),(0,n.jsx)("p",{className:"text-xs text-muted-foreground",children:"If empty, the public page uses the post title only."})]}),(0,n.jsxs)("div",{className:"grid gap-2",children:[(0,n.jsx)(tH,{htmlFor:"seo_description",children:"Meta description"}
1),(0,n.jsx)(rP.T,{id:"seo_description",value:H.seo_description,onChange:e=>rT("seo_description",e.target.value),rows:4})]}),(0,n.jsxs)("div",{className:"grid md:grid-cols-2 gap-4",children:[(0,n.jsxs)("div",{className:"grid gap-2",children:[(0,n.jsx)(tH,{htmlFor:"focus_keyword",children:"Focus keyword"}),(0,n.jsx)(tR.p,{id:"focus_keyword",value:H.focus_keyword,onChange:e=>rT("focus_keyword",e.target.value)})]}),(0,n.jsxs)("div",{className:"grid gap-2",children:[(0,n.jsx)(tH,{htmlFor:"meta_keywords",children:"Meta keywords"}),(0,n.jsx)(tR.p,{id:"meta_keywords",value:H.meta_keywords,onChange:e=>rT("meta_keywords",e.target.value),placeholder:"sourcing, manufacturing, bangladesh"})]})]})]}),(0,n.jsxs)("div",{className:"rounded-2xl border bg-card p-5 space-y-4",children:[(0,n.jsxs)("div",{className:"border-b border-border pb-3",children:[(0,n.jsx)("p",{className:"text-sm font-medium",children:"Structured data (JSON-LD)"}),(0,n.jsx)("p",{className:"text-xs text-muted-foreground mt-1 leading-snug",children:"Search engines read this from the live post URL. Built from SEO fields, dates, author, category, keywords, and featured image."})]}),(0,n.jsxs)("div",{className:"grid gap-2",children:[(0,n.jsx)(tH,{htmlFor:"seo_schema_type",children:"Schema.org type"}),(0,n.jsxs)(rl,{value:H.seo_schema_type||"BlogPosting",onValueChange:e=>rT("seo_schema_type",e),children:[(0,n.jsx)(rd,{id:"seo_schema_type",children:(0,n.jsx)(ro,{placeholder:"Type"})}),(0,n.jsx)(rm,{children:eU.map(e=>(0,n.jsxs)(rh,{value:e,children:[e,"BlogPosting"===e?" (recommended for blog posts)":""]},e))})]})]}),(0,n.jsxs)("div",{className:"grid gap-2",children:[(0,n.jsx)(tH,{htmlFor:"schema_json_ld_preview",className:"text-xs text-muted-foreground",children:"Preview (read-only)"}),(0,n.jsx)(rP.T,{id:"schema_json_ld_preview",readOnly:!0,rows:12,value:nl,className:"resize-y font-mono text-[11px] leading-relaxed min-h-[12rem]",spellCheck:!1})]}),(0,n.jsxs)("p",{className:"text-[11px] text-muted-foreground leading-snug",children:["If save fails with an unknown column, run"," ",(0,n.jsx)("code",{className:"rounded bg-muted px-1 py-0.5 text-[10px]",children:"scripts/add-blog-posts-seo-schema-type.sql"})," ","in Supabase."]})]}),(0,n.jsxs)("div",{className:"rounded-2xl border bg-card p-5 space-y-3",children:[(0,n.jsxs)("div",{className:"flex flex-col gap-3 sm:flex-row sm:items-start sm:justify-between",children:[(0,n.jsxs)("div",{className:"min-w-0",children:[(0,n.jsx)("p",{className:"text-sm font-medium",children:"SEO health"}),(0,n.jsx)("p",{className:"text-xs text-muted-foreground mt-0.5 leading-snug",children:"Live checks on title, meta, duplicate title, body (extra H1 vs title, alt, links), cover image."})]}),(0,n.jsxs)("div",{className:"flex flex-wrap items-center gap-2 shrink-0",children:[(0,n.jsxs)(L.Button,{type:"button",variant:"secondary",size:"sm",className:"gap-1.5",disabled:ey||!tG||ni.issues.length+ni.hints.length===0,onClick:()=>void nm(),title:tG?ni.issues.length+ni.hints.length===0?"No issues or hints to fix":"Build a fix preview (auto H1→H2, meta/alt fixes — not links; use content editor for links)":"Configure API Settings first",children:[(0,n.jsx)(rV.A,{className:"h-3.5 w-3.5 ".concat(ey?"animate-pulse":""),"aria-hidden":!0}),ey?"Working…":"AI Fix"]}),(0,n.jsx)("span",{className:(0,b.cn)("rounded-md border px-2 py-0.5 text-xs font-medium tabular-nums","ok"===ni.level&&"border-emerald-300/80 bg-emerald-50 text-emerald-900 dark:border-emerald-700 dark:bg-emerald-950/50 dark:text-emerald-100","warn"===ni.level&&"border-amber-300/80 bg-amber-50 text-amber-950 dark:border-amber-700 dark:bg-amber-950/40 dark:text-amber-100","bad"===ni.level&&"border-destructive/40 bg-destructive/10 text-destructive dark:bg-destructive/20"),children:"ok"===ni.level?"Good":"warn"===ni.level?"Review":"Fix"})]})]}),(0,n.jsxs)("div",{className:"space-y-2.5 rounded-lg border border-border/70 bg-muted/20 px-3 py-2.5 text-xs",children:[(0,n.jsxs)("div",{children:[(0,n.jsxs)("div",{className:"flex justify-between gap-2 text-muted-foreground mb-1",children:[(0,n.jsx)("span",{children:"SEO title (effective)"}),(0,n.jsxs)("span",{className:(0,b.cn)("tabular-nums",nc>tp.seoTitleMax&&"text-destructive font-medium"),children:[nc,"/",tp.seoTitleMax]})]}),(0,n.jsx)(nk,{value:Math.min(100,nc/Math.max(1,tp.seoTitleMax)*100),className:"h-1.5"})]}),(0,n.jsxs)("div",{children:[(0,n.jsxs)("div",{className:"flex justify-between gap-2 text-muted-foreground mb-1",children:[(0,n.jsx)("span",{children:"Meta description (effective)"}),(0,n.jsxs)("span",{className:(0,b.cn)("tabular-nums",nu>tp.metaDescriptionMax&&"text-destructive font-medium"),children:[nu,"/",tp.metaDescriptionMax]})]}),(0,n.jsx)(nk,{value:Math.min(100,nu/Math.max(1,tp.metaDescriptionMax)*100),className:"h-1.5"})]})]}),ni.issues.length>0?(0,n.jsx)("ul",{className:"space-y-1.5 text-xs leading-snug",children:ni.issues.map((e,t)=>(0,n.jsxs)("li",{className:"flex gap-2 text-destructive",children:[(0,n.jsx)(av.A,{className:"h-3.5 w-3.5 shrink-0 mt-0.5","aria-hidden":!0}),(0,n.jsx)("span",{children:e})]},"issue-".concat(t)))}):null,ni.hints.length>0?(0,n.jsx)("ul",{className:"space-y-1.5 text-xs leading-snug text-muted-foreground",children:ni.hints.map((e,t)=>(0,n.jsxs)("li",{className:"flex gap-2",children:[(0,n.jsx)(ay.A,{className:"h-3.5 w-3.5 shrink-0 mt-0.5 text-amber-600 dar
1k:text-amber-400","aria-hidden":!0}),(0,n.jsx)("span",{children:e})]},"hint-".concat(t)))}):null,0===ni.issues.length&&0===ni.hints.length?(0,n.jsx)("p",{className:"text-xs text-muted-foreground",children:"No issues flagged — keep publishing best practices in mind."}):null,(0,n.jsxs)("div",{className:"border-t border-border pt-3 space-y-2",children:[(0,n.jsx)("p",{className:"text-xs font-medium text-muted-foreground",children:"Structure (body HTML)"}),(0,n.jsx)("div",{className:"grid grid-cols-3 sm:grid-cols-6 gap-2 text-xs",children:[1,2,3,4,5,6].map(e=>{let t="h".concat(e);return(0,n.jsxs)("div",{className:"flex items-center justify-between gap-2 rounded-md border border-border/60 bg-muted/30 px-2 py-1.5 font-mono tabular-nums",children:[(0,n.jsxs)("span",{className:"text-muted-foreground",children:["H",e]}),(0,n.jsx)("span",{children:ni.bodyStats.headingCounts[t]})]},t)})}),(0,n.jsxs)("p",{className:"text-xs text-muted-foreground leading-relaxed",children:["Images ",ni.bodyStats.imagesTotal,ni.bodyStats.imagesMissingAlt>0?(0,n.jsxs)("span",{className:"text-amber-800 dark:text-amber-200/90",children:[" ","\xb7 ",ni.bodyStats.imagesMissingAlt," missing alt"]}):null,(0,n.jsx)("br",{}),"Links: ",ni.bodyStats.internalLinkCount," internal \xb7 ",ni.bodyStats.externalLinkCount," ","external"]})]})]})]}),(0,n.jsx)("div",{className:"space-y-4",children:(0,n.jsxs)("div",{className:"rounded-2xl border bg-card p-5",children:[(0,n.jsx)("p",{className:"text-sm font-medium mb-2",children:"Google preview"}),(0,n.jsxs)("div",{className:"rounded-xl border bg-background p-4",children:[(0,n.jsx)("p",{className:"text-sm text-blue-700 font-medium leading-snug",children:nr||"SEO title preview"}),(0,n.jsx)("p",{className:"text-xs text-green-700 mt-1 truncate",children:rN||"https://your-site.com/slug"}),(0,n.jsx)("p",{className:"text-sm text-muted-foreground mt-2 leading-relaxed",children:nn||"Meta description preview…"})]})]})})]})}),(0,n.jsxs)(rt,{value:"social",className:"mt-4",children:[(0,n.jsx)("p",{className:"text-xs text-muted-foreground mb-4 max-w-3xl",children:"If you leave these fields empty, shares use the same title as SEO title (SEO tab), the meta description for both descriptions, and the featured image for both OG and Twitter images."}),(0,n.jsxs)("div",{className:"grid lg:grid-cols-2 gap-6",children:[(0,n.jsxs)("div",{className:"rounded-2xl border bg-card p-5 space-y-4",children:[(0,n.jsx)("p",{className:"text-sm font-medium",children:"OpenGraph"}),(0,n.jsxs)("div",{className:"grid gap-2",children:[(0,n.jsx)(tH,{htmlFor:"og_title",children:"OG title"}),(0,n.jsx)(tR.p,{id:"og_title",value:H.og_title,onChange:e=>rT("og_title",e.target.value)})]}),(0,n.jsxs)("div",{className:"grid gap-2",children:[(0,n.jsx)(tH,{htmlFor:"og_description",children:"OG description"}),(0,n.jsx)(rP.T,{id:"og_description",value:H.og_description,onChange:e=>rT("og_description",e.target.value),rows:4})]}),(0,n.jsx)(rF,{label:"OG image (optional)",value:H.og_image_url,onChange:e=>rT("og_image_url",e),useMediaPicker:!0,mediaPickerTitle:"Open Graph image",mediaPickerConfirmLabel:"Use image",maxWidth:2560,maxHeight:2560,quality:.92,onEditAttachment:e=>rD({src:e})})]}),(0,n.jsxs)("div",{className:"rounded-2xl border bg-card p-5 space-y-4",children:[(0,n.jsx)("p",{className:"text-sm font-medium",children:"Twitter"}),(0,n.jsxs)("div",{className:"grid gap-2",children:[(0,n.jsx)(tH,{htmlFor:"twitter_title",children:"Twitter title"}),(0,n.jsx)(tR.p,{id:"twitter_title",value:H.twitter_title,onChange:e=>rT("twitter_title",e.target.value)})]}),(0,n.jsxs)("div",{className:"grid gap-2",children:[(0,n.jsx)(tH,{htmlFor:"twitter_description",children:"Twitter description"}),(0,n.jsx)(rP.T,{id:"twitter_description",value:H.twitter_description,onChange:e=>rT("twitter_description",e.target.value),rows:4})]}),(0,n.jsx)(rF,{label:"Twitter image (optional)",value:H.twitter_image_url,onChange:e=>rT("twitter_image_url",e),useMediaPicker:!0,mediaPickerTitle:"Twitter image",mediaPickerConfirmLabel:"Use image",maxWidth:2560,maxHeight:2560,quality:.92,onEditAttachment:e=>rD({src:e})})]})]})]}),(0,n.jsx)(rt,{value:"advanced",className:"mt-4",children:(0,n.jsxs)("div",{className:"grid lg:grid-cols-[1fr_360px] gap-6",children:[(0,n.jsxs)("div",{className:"rounded-2xl border bg-card p-5 space-y-4",children:[(0,n.jsxs)("div",{className:"grid gap-2",children:[(0,n.jsx)(tH,{htmlFor:"canonical_url",children:"Canonical URL (optional)"}),(0,n.jsx)(tR.p,{id:"canonical_url",value:H.canonical_url,onChange:e=>rT("canonical_url",e.target.value),placeholder:rN||"https://…"})]}),(0,n.jsxs)("div",{className:"flex items-center justify-between rounded-xl border px-4 py-3",children:[(0,n.jsxs)("div",{children:[(0,n.jsx)("p",{className:"text-sm font-medium",children:"Index"}),(0,n.jsx)("p",{className:"text-xs text-muted-foreground",children:"Allow search engines to index this post"})]}),(0,n.jsx)(rL,{checked:!!H.robots_index,onCheckedChange:e=>rT("robots_index",e)})]}),(0,n.jsxs)("div",{className:"flex items-center justify-between rounded-xl border px-4 py-3",children:[(0,n.jsxs)("div",{children:[(0,n.jsx)("p",{className:"text-sm font-medium",children:"Follow"}),(0,n.jsx)("p",{className:"text-xs text-muted-foreground",children:"Allow crawlers to follow links"})]}),(0,n.jsx)(rL,{checked:!!H.robots_follow,onCheckedChange:e=>rT("robots_follow",e)})]})]}),x?(0,n.jsx)("div",{className:"rounded-2xl border bg-card p-5 text-sm text-muted-foreground",children:"Save the post first to enable delete."}):(0,n.jsxs)("div",{className:"rounded-2xl border border-destructive/30 bg-destructive/5 p-5 space-y-3",children:[(0,n.jsx)("p",{className:"text-sm font-medium text-destructive",children:"Danger zone"}),(0,n.jsx)("p",{className:"text-xs text-muted-foreground",children:"Moves the post to Trash (hidden from the site). Permanently delete it from the Trash list."}),(0,n.jsx)(L.Button,{type:"button",variant:"destructive",onClick:()=>rA.mutate(),disabled:rA.isPending,children:rA.isPending?"Moving…":"Move to trash"})]})]})})]})]})},{})}),(0,n.jsx)(s.qh,{path:"media",element:(0,n.jsx)(function(){let{isAdmin:e}=I(),t=(0,o.jE)(),r=(0,a.useRef)(null),[s,i]=(0,a.useState)(""),[l,d]=(0,a.useState)(1),[c,u]=(0,a.useState)(!1),[m,h]=(0,a.useState)(!1),[p,g]=(0,a.useState)(0),[x,v]=(0,a.useState)(null),{data:y=[],isLoading:b,isError:j,error:w,refetch:_}=(0,eK.I)({queryKey:["admin","cms-media",eC],queryFn:()=>eP(T.N),staleTime:2e4}),N=(0,a.useMemo)(()=>y.map(e=>({objectPath:e,storageUrl:eI(e,T.N)})),[y]),k=(0,a.useMemo)(()=>{let e=s.trim().toLowerCase();return e?N.filter(t=>{let{objectPath:r}=t;return r.toLowerCase().includes(e)}):N},[N,s]),S=k.length,C=Math.max(1,Math.ceil(S/20));(0,a.useEffect)(()=>{d(1)},[s]),(0,a.useEffect)(()=>{d(e=>Math.min(Math.max(1,e),C))},[C]);let A=Math.min(Math.max(1,l),C),E=(A-1)*20,q=k.slice(E,E+20),M=0===S?0:E+1,P=Math.min(E+20,S),O=(0,a.useCallback)(e=>{let t=N.findIndex(t=>t.objectPath===e);g(t>=0?t:0),h(!0)},[N]),R=(0,a.useCallback)(async e=>{var r;if(e&&(null==(r=e.type)?void 0:r.startsWith("image/"))){u(!0);
1try{let r=await rR(e,{maxWidth:1600,maxHeight:1600,quality:.82,mimeType:"image/webp",forceTargetMime:!0}),n=rD(r.name)||"webp",a=eq(e.name,"jpg"===n||"jpeg"===n?"jpg":"png"===n||"gif"===n?n:"webp"),{error:s}=await T.N.storage.from(eC).upload(a,r,{upsert:!0,contentType:r.type||void 0});if(s)throw s;await t.refetchQueries({queryKey:["admin","cms-media",eC]});let i=(t.getQueryData(["admin","cms-media",eC])||[]).indexOf(a);g(i>=0?i:0),h(!0),f({title:"Uploaded",description:"File is in your library."})}catch(e){f({title:"Upload failed",description:(null==e?void 0:e.message)||"Unknown error",variant:"destructive"})}finally{u(!1)}}},[t]),D=(0,tO.n)({mutationFn:async e=>{let{error:t}=await T.N.storage.from(eC).remove([e]);if(t)throw t;await eH(e)},onSuccess:async()=>{await t.invalidateQueries({queryKey:["admin","cms-media",eC]}),await t.invalidateQueries({queryKey:["admin","cms-media-meta"]}),f({title:"File removed",description:"Removed from storage and media metadata."}),v(null),h(!1),g(0)},onError:e=>{f({title:"Delete failed",description:(null==e?void 0:e.message)||"Check storage policies.",variant:"destructive"})}});return(0,n.jsxs)("div",{className:"space-y-6",children:[(0,n.jsxs)("div",{className:"flex flex-wrap items-start justify-between gap-4",children:[(0,n.jsxs)("div",{children:[(0,n.jsx)("h1",{className:"text-2xl font-semibold",children:"Media"}),(0,n.jsx)("p",{className:"mt-1 text-sm text-muted-foreground",children:"Upload images and manage the shared CMS library (same files as in posts and products)."})]}),(0,n.jsxs)("div",{className:"flex flex-wrap items-center gap-2",children:[(0,n.jsx)("input",{ref:r,type:"file",accept:"image/*",className:"hidden",disabled:c,onChange:e=>{var t;let r=null==(t=e.target.files)?void 0:t[0];e.target.value="",R(r)}}),(0,n.jsxs)(L.Button,{type:"button",disabled:c,className:"gap-2",onClick:()=>{var e;return null==(e=r.current)?void 0:e.click()},children:[(0,n.jsx)(aB.A,{className:"h-4 w-4"}),c?"Uploading…":"Upload"]})]})]}),(0,n.jsxs)("div",{className:"flex flex-wrap items-center gap-3",children:[(0,n.jsx)(tR.p,{value:s,onChange:e=>i(e.target.value),placeholder:"Search files…",className:"max-w-sm",type:"search"}),(0,n.jsx)("p",{className:"text-sm text-muted-foreground",children:b?"Loading…":"".concat(S," file").concat(1===S?"":"s")}),j?(0,n.jsx)(L.Button,{type:"button",variant:"outline",size:"sm",onClick:()=>void _(),children:"Retry load"}):null]}),j?(0,n.jsxs)("div",{role:"alert",className:"rounded-xl border border-destructive/40 bg-destructive/10 px-4 py-3 text-sm text-destructive",children:[(0,n.jsx)("p",{className:"font-medium",children:"Could not load media library"}),(0,n.jsx)("p",{className:"mt-1 opacity-90",children:(null==w?void 0:w.message)||"Storage list failed — check policies and that you are logged in as an admin."}),(0,n.jsxs)("p",{className:"mt-2 text-xs opacity-90",children:["If you ran ",(0,n.jsx)("span",{className:"font-mono",children:"harden-cms-uploads-storage-policies.sql"}),", apply"," ",(0,n.jsx)("span",{className:"font-mono",children:"scripts/fix-cms-uploads-admin-list-policy.sql"})," in the Supabase SQL editor so admins can list objects."]})]}):null,(0,n.jsxs)("div",{className:"rounded-2xl border border-dashed border-border/80 bg-muted/20 px-4 py-8 text-center sm:px-8",onDragOver:e=>e.preventDefault(),onDrop:e=>{var t,r;e.preventDefault(),R(null==(r=e.dataTransfer)||null==(t=r.files)?void 0:t[0])},children:[(0,n.jsx)(K.A,{className:"mx-auto h-10 w-10 text-muted-foreground/80","aria-hidden":!0}),(0,n.jsx)("p",{className:"mt-3 text-sm text-muted-foreground",children:"Drop images here to upload, or use Upload."})]}),b?(0,n.jsx)("p",{className:"py-16 text-center text-sm text-muted-foreground",children:"Loading library…"}):0===k.length?(0,n.jsxs)("div",{className:"py-16 text-center text-sm text-muted-foreground space-y-4 max-w-lg mx-auto",children:[(0,n.jsx)("p",{children:0===N.length?"No images yet — upload a file to get started.":"No matches for your search."}),0===N.length&&e&&!s.trim()?(0,n.jsxs)("div",{role:"note",className:"rounded-xl border border-amber-500/40 bg-amber-500/10 px-4 py-3 text-left text-amber-950 dar
1k:text-amber-100",children:[(0,n.jsx)("p",{className:"font-medium text-foreground",children:"Still empty but files exist in Supabase Storage?"}),(0,n.jsxs)("p",{className:"mt-2 text-xs leading-relaxed",children:["After running ",(0,n.jsx)("span",{className:"font-mono",children:"harden-cms-uploads-storage-policies.sql"}),", listing is blocked until you add an admin SELECT policy. Run ",(0,n.jsx)("span",{className:"font-mono",children:"scripts/fix-cms-uploads-admin-list-policy.sql"})," in the Supabase SQL Editor, then refresh this page. Confirm your user has"," ",(0,n.jsxs)("span",{className:"font-mono",children:["role = ","'","admin","'"]})," in ",(0,n.jsx)("span",{className:"font-mono",children:"public.user_roles"}),"."]})]}):null]}):(0,n.jsxs)(n.Fragment,{children:[(0,n.jsx)("ul",{className:"grid grid-cols-2 gap-3 sm:grid-cols-3 md:grid-cols-5 sm:gap-4",children:q.map(e=>{let{objectPath:t,storageUrl:r}=e;return(0,n.jsx)("li",{className:"min-w-0",children:(0,n.jsxs)("button",{type:"button",className:"w-full overflow-hidden rounded-xl border border-border/80 bg-card text-left shadow-sm outline-none transition hover:border-primary/50 focus-visible:ring-2 focus-visible:ring-ring",onClick:()=>O(t),children:[(0,n.jsx)("div",{className:"relative aspect-square bg-muted",children:(0,n.jsx)("img",{src:r,alt:"",className:"h-full w-full object-cover",loading:"lazy"})}),(0,n.jsx)("p",{className:"truncate px-2 py-2 font-mono text-[10px] text-muted-foreground",title:t,children:t.split("/").pop()})]})},t)})}),(0,n.jsx)("nav",{className:"text-sm text-muted-foreground","aria-label":"Media library pagination",children:(0,n.jsxs)("div",{className:"flex flex-wrap items-center justify-center gap-x-6 gap-y-2 text-center pt-2",children:[(0,n.jsxs)("p",{children:["Showing ",(0,n.jsx)("span",{className:"font-medium text-foreground",children:M}),"–",(0,n.jsx)("span",{className:"font-medium text-foreground",children:P})," of"," ",(0,n.jsx)("span",{className:"font-medium text-foreground",children:S}),s.trim()?(0,n.jsx)("span",{className:"text-muted-foreground",children:" (filtered)"}):null]}),C>1?(0,n.jsxs)("div",{className:"flex flex-wrap items-center justify-center gap-2",children:[(0,n.jsx)(L.Button,{type:"button",variant:"outline",size:"sm",disabled:A<=1,onClick:()=>d(e=>Math.max(1,e-1)),children:"Previous"}),(0,n.jsxs)("span",{className:"min-w-[7rem] px-1 tabular-nums sm:min-w-[8.5rem]",children:["Page ",(0,n.jsx)("span",{className:"font-medium text-foreground",children:A})," of"," ",(0,n.jsx)("span",{className:"font-medium text-foreground",children:C})]}),(0,n.jsx)(L.Button,{type:"button",variant:"outline",size:"sm",disabled:A>=C,onClick:()=>d(e=>Math.min(C,e+1)),children:"Next"})]}):null]})})]}),(0,n.jsx)(np,{open:m&&N.length>0,onOpenChange:e=>{e||h(!1)},items:N,activeIndex:p,onActiveIndexChange:g,onRequestDelete:e=>{h(!1),v(e)},onStorageRenamed:(e,t,r)=>{"number"==typeof r&&r>=0&&g(r)}}),(0,n.jsx)(er,{open:!!x,onOpenChange:e=>!e&&v(null),children:(0,n.jsxs)(es,{children:[(0,n.jsxs)(ei,{children:[(0,n.jsx)(eo,{children:"Delete this file?"}),(0,n.jsxs)(ed,{children:["This removes the object from Supabase Storage. Any content that still uses this URL will show a broken image until you update it.",x?(0,n.jsx)("span",{className:"mt-2 block break-all font-mono text-xs text-foreground",children:x}):null]})]}),(0,n.jsxs)(el,{children:[(0,n.jsx)(eu,{children:"Cancel"}),(0,n.jsx)(ec,{className:"bg-destructive text-destructive-foreground hover:bg-destructive/90",onClick:()=>x&&D.mutate(x),children:"Delete"})]})]})})]})},{})}),(0,n.jsx)(s.qh,{path:"pages",element:(0,n.jsx)(function(){let[e,t]=(0,a.useState)(""),{data:r={}}=(0,eK.I)({queryKey:["admin","page_seo"],queryFn:az}),{data:s=new Set}=(0,eK.I)({queryKey:["admin","page_content_routes"],queryFn:aK}),l=(0,a.useMemo)(()=>{let t=e.trim().toLowerCase();return aU.ZZ.filter(e=>!t||e.route.toLowerCase().includes(t)||e.label.toLowerCase().includes(t))},[e]);return(0,n.jsxs)("div",{className:"space-y-6",children:[(0,n.jsx)("div",{className:"flex items-start justify-between gap-4 flex-wrap",children:(0,n.jsxs)("div",{children:[(0,n.jsx)("h1",{className:"text-2xl font-semibold",children:"Pages"}),(0,n.jsx)("p",{className:"text-sm text-muted-foreground mt-1",children:"Edit content and SEO for every public page — section by section."})]})}
1),(0,n.jsx)(tR.p,{value:e,onChange:e=>t(e.target.value),placeholder:"Search pages…",className:"max-w-sm"}),(0,n.jsxs)("div",{className:"rounded-2xl border bg-card overflow-hidden",children:[(0,n.jsxs)("div",{className:"grid grid-cols-[1fr_180px_100px_100px_120px] border-b px-4 py-3 text-xs font-medium text-muted-foreground",children:[(0,n.jsx)("div",{children:"Page"}),(0,n.jsx)("div",{children:"Route"}),(0,n.jsx)("div",{className:"text-center",children:"Content"}),(0,n.jsx)("div",{className:"text-center",children:"SEO"}),(0,n.jsx)("div",{className:"text-right",children:"Actions"})]}),0===l.length?(0,n.jsx)("div",{className:"px-4 py-8 text-sm text-muted-foreground text-center",children:"No pages found."}):(0,n.jsx)("div",{className:"divide-y",children:l.map(e=>{let t=r[e.route],a=s.has(e.route),l=!!(null==t?void 0:t.seo_title),o=!t||!1!==t.robots_index;return(0,n.jsxs)("div",{className:"grid grid-cols-[1fr_180px_100px_100px_120px] items-center px-4 py-3 hover:bg-muted/30 transition-colors",children:[(0,n.jsxs)("div",{children:[(0,n.jsx)("p",{className:"text-sm font-medium",children:e.label}),(0,n.jsxs)("p",{className:"text-xs text-muted-foreground",children:[e.sections.length," sections"]})]}),(0,n.jsx)("div",{className:"font-mono text-xs text-muted-foreground truncate pr-2",children:e.route}),(0,n.jsx)("div",{className:"text-center",children:a?(0,n.jsx)(tB,{variant:"secondary",className:"text-[10px] bg-emerald-100 text-emerald-700 border-emerald-200",children:"Edited"}):(0,n.jsx)(tB,{variant:"outline",className:"text-[10px] text-muted-foreground",children:"Default"})}),(0,n.jsx)("div",{className:"text-center",children:l?(0,n.jsx)(tB,{variant:"secondary",className:"text-[10px] ".concat(o?"bg-emerald-100 text-emerald-700 border-emerald-200":"bg-amber-100 text-amber-700 border-amber-200"),children:o?"Set":"Noindex"}):(0,n.jsx)(tB,{variant:"outline",className:"text-[10px] text-muted-foreground",children:"None"})}),(0,n.jsx)("div",{className:"flex items-center justify-end gap-2",children:(0,n.jsx)(L.Button,{asChild:!0,size:"sm",variant:"outline",className:"gap-1.5",children:(0,n.jsxs)(i.N_,{to:"/admin/pages/edit/?path=".concat(encodeURIComponent(e.route)),children:[(0,n.jsx)(aF.A,{className:"w-3 h-3"}),"Edit"]})})})]},e.route)})})]}),(0,n.jsxs)("p",{className:"text-xs text-muted-foreground",children:[l.length," page",1!==l.length?"s":""," in registry. Content edits override hardcoded defaults; fallbacks apply automatically when no DB row exists."]})]})},{})}),(0,n.jsx)(s.qh,{path:"pages/edit",element:(0,n.jsx)(function(){var e;let[t]=(0,i.ok)();(0,s.Zp)();let r=(0,o.jE)(),l=function(e){if(!e)return"/";let t=String(e).trim();if(!t||"/"===t)return"/";let r=t.startsWith("/")?t:"/".concat(t);return r.endsWith("/")?r:"".concat(r,"/")}(t.get("path")||"/"),d=(0,aU.dj)(l),{data:c={},isLoading:u}=(0,eK.I)({queryKey:["admin","page_content",l],queryFn:()=>aH(l),enabled:!!l}),[m,h]=(0,a.useState)({}),[p,g]=(0,a.useState)(!1),x=(0,a.useRef)(!1);(0,a.useEffect)(()=>{if(u||x.current||(x.current=!0,!d))return;let e={};for(let t of d.sections)e[t.key]={...t.defaults||{},...c[t.key]||{}};h(e)},[u,c,d]);let v=(0,tO.n)({mutationFn:async()=>{await aV(l,m)},onSuccess:async()=>{g(!1),await r.invalidateQueries({queryKey:["public","page_content",l]}),await r.invalidateQueries({queryKey:["admin","page_content",l]}),f({title:"Content saved",description:"Page content updated successfully."})},onError:e=>{f({title:"Save failed",description:(null==e?void 0:e.message)||"Unknown error",variant:"destructive"})}});return d?u?(0,n.jsxs)("div",{className:"space-y-4 animate-pulse",children:[(0,n.jsx)("div",{className:"h-8 bg-muted rounded w-48"}),[1,2,3].map(e=>(0,n.jsx)("div",{className:"h-32 bg-muted rounded-2xl"},e))]}):(0,n.jsxs)("div",{className:"space-y-6",children:[(0,n.jsx)("header",{className:"rounded-xl border border-border bg-card p-4 shadow-sm sm:p-5",children:(0,n.jsxs)("div",{className:"flex flex-col gap-4 lg:flex-row lg:items-center lg:justify-between",children:[(0,n.jsxs)("div",{className:"min-w-0 space-y-3 flex-1",children:[(0,n.jsxs)(i.N_,{to:"/admin/pages/",className:"inline-flex items-center gap-1.5 text-sm text-muted-foreground hover:text-foreground transition-colors",children:[(0,n.jsx)(rU.A,{className:"w-4 h-4 shrink-0"}),"Back to Pages"]}),(0,n.jsxs)("div",{className:"space-y-2",children:[(0,n.jsx)("h1",{className:"text-2xl font-semibold tracking-tight text-foreground sm:text-3xl",children:d.label}),(0,n.jsxs)("div",{className:"flex flex-wrap items-center gap-2",children:[(0,n.jsx)("span",{className:"text-xs font-medium uppercase tracking-wider text-muted-foreground",children:"URL"}),(0,n.jsx)("code",{className:"rounded-md border border-border bg-muted/60 px-2.5 py-1 text-xs font-mono text-muted-foreground",children:l})]})]})]}),(0,n.jsxs)("div",{className:"flex shrink-0 flex-wrap items-center gap-2",children:[p?(0,n.jsx)("span",{className:"text-xs text-amber-700 dark:text-amber-400 bg-amber-50 dark:bg-amber-950/50 border border-amber-200 dark:border-amber-900 rounded-full px-3 py-1",children:"Unsaved changes"}):null,(0,n.jsxs)(L.Button,{type:"button",onClick:()=>v.mutate(),disabled:v.isPending||!p,className:"gap-2",children:[(0,n.jsx)(aG.A,{className:"w-4 h-4"}),v.isPending?"Saving…":"Save All"]})]})]})}),(0,n.jsxs)(t9,{defaultValue:"content",children:[(0,n.jsxs)(t7,{className:"w-full max-w-xs",children:[(0,n.jsx)(re,{value:"content",className:"flex-1",children:"Content"}),(0,n.jsx)(re,{value:"seo",className:"flex-1",children:"SEO"})]}),(0,n.jsxs)(rt,{value:"content",className:"space-y-3 mt-4",children:[d.sections.map(e=>(0,n.jsx)(a$,{sectionDef:e,data:m[e.key]||e.defaults,onChange:t=>{var r;return r=e.key,void(h(e=>({...e,[r]:t})),g(!0))}},e.key)),v.isError?(0,n.jsxs)("div",{className:"rounded-lg border border-destructive/30 bg-destructive/10 px-3 py-2 text-sm text-destructive",children:["Save failed: ",null==(e=v.error)?void 0:e.message]}):null,(0,n.jsx)("div",{className:"flex justify-end pt-2",children:(0,n.jsxs)(L.Button,{type:"button",onClick:()=>v.mutate(),disabled:v.isPending||!p,className:"gap-2",children:[(0,n.jsx)(aG.A,{className:"w-4 h-4"}),v.isPending?"Saving…":"Save All"]})})]}),(0,n.jsx)(rt,{value:"seo",className:"mt-4",children:(0,n.jsxs)("div",{className:"rounded-2xl border bg-card p-6",children:[(0,n.jsx)("h2",{className:"text-base font-semibold mb-4",children:"SEO Settings"}),(0,n.jsx)(aX,{routePath:l,pageDef:d})]})})]})]}):(0,n.jsxs)("div",{className:"space-y-4",children:[(0,n.jsxs)("div",{className:"rounded-xl border border-border bg-card p-4 shadow-sm space-y-3",children:[(0,n.jsxs)(i.N_,{to:"/admin/pages/",className:"inline-flex items-center gap-1.5 text-sm text-muted-foreground hover:text-foreground transition-colors",children:[(0,n.jsx)(rU.A,{className:"w-4 h-4 shrink-0"}),"Back to Pages"]}),(0,n.jsxs)("div",{className:"space-y-1",children:[(0,n.jsx)("h1",{className:"text-xl font-semibold tracking-tight",children:"Page not in registry"}),(0,n.jsx)("code",{className:"inline-block rounded-md border border-border bg-muted/60 px-2 py-0.5 text-xs font-mono text-muted-foreground",children:l})]})]}),(0,n.jsxs)("p",{className:"text-muted-foreground text-sm",children:["This route is not defined in ",(0,n.jsx)("code",{className:"bg-muted px-1 py-0.5 rounded text-xs",children:"pagesRegistry.js"}),". You can still edit SEO below, or add the page to the registry to enable content editing."]}),(0,n.jsx)("div",{className:"rounded-2xl border bg-card p-6",children:(0,n.jsx)(aX,{routePath:l,pageDef:{label:l}})})]})},{})}),(0,n.jsx)(s.qh,{path:"products/reviews",element:(0,n.jsx)(function(){let e=(0,o.jE)(),[t,r]=(0,a.useState)("pending"),{data:s=[],isLoading:l,error:d}=(0,eK.I)({queryKey:["admin","product_reviews",t],queryFn:()=>aZ(t)}),c=(0,tO.n)({mutationFn:async e=>{let{id:t,patch:r}=e,{error:n}=await T.N.from("product_reviews").update({...r,updated_at:new Date().toISOString()}).eq("id",t);if(n)throw n},onSuccess:()=>e.invalidateQueries({queryKey:["admin","product_reviews"]})}),u=(0,tO.n)({mutationFn:async e=>{let{error:t}=await T.N.from("product_reviews").delete().eq("id",e);if(t)throw t},onSuccess:()=>e.invalidateQueries({queryKey:["admin","product_reviews"]})});return(0,n.jsxs)("div",{className:"space-y-6",children:[(0,n.jsxs)("div",{className:"flex flex-wrap items-end justify-between gap-4",children:[(0,n.jsxs)("div",{children:[(0,n.jsxs)("p",{className:"text-sm text-muted-foreground mb-1",children:[(0,n.jsx)(i.N_,{to:"/admin/products/",className:"hover:underline",children:"Products"})," ","/ Reviews"]}),(0,n.jsx)("h1",{className:"text-2xl font-semibold",children:"Product reviews"}),(0,n.jsx)("p",{className:"text-sm text-muted-foreground mt-1",children:"Moderate reviews (approve or mark spam). Public site shows approved only."})]}),(0,n.jsxs)("div",{className:"flex items-center gap-2",children:[(0,n.jsx)("span",{className:"text-sm text-muted-foreground",children:"Filter"}),(0,n.jsxs)(rl,{value:t,onValueChange:r,children:[(0,n.jsx)(rd,{className:"w-[160px]",children:(0,n.jsx)(ro,{})}),(0,n.jsxs)(rm,{children:[(0,n.jsx)(rh,{value:"all",children:"All"}),(0,n.jsx)(rh,{value:"pending",children:"Pending"}),(0,n.jsx)(rh,{value:"approved",children:"Approved"}),(0,n.jsx)(rh,{value:"spam",children:"Spam"})]})]})]})]}),d?(0,n.jsxs)("div",{className:"rounded-lg border border-destructive/30 bg-destructive/10 px-3 py-2 text-sm text-destructive",children:[(0,n.jsx)("p",{children:d.message}),(0,n.jsxs)("p",{className:"text-xs mt-1",children:["Run ",(0,n.jsx)("code",{className:"rounded bg-background px-1",children:"scripts/ensure-product-extensions.sql"}),"."]})]}):null,(0,n.jsx)("div",{className:"rounded-2xl border bg-card overflow-hidden",children:l?(0,n.jsx)("div",{className:"p-8 text-sm text-muted-foreground text-center",children:"Loading…"}):0===s.length?(0,n.jsx)("div",{className:"p-8 text-sm text-muted-foreground text-center",children:"No reviews."}):(0,n.jsx)("ul",{className:"divide-y",children:s.map(e=>(0,n.jsxs)("li",{className:"p-4 space-y-2",children:[(0,n.jsxs)("div",{className:"flex flex-wrap items-center justify-between gap-2",children:[(0,n.jsxs)("div",{className:"flex flex-wrap items-center gap-2",children:[(0,n.jsx)(tB,{variant:"approved"===e.status?"default":"spam"===e.status?"destructive":"secondary",children:e.status}),(0,n.jsx)("span",{className:"font-medium",children:e.title||"(no title)"}),(0,n.jsxs)("span",{className:"text-sm text-muted-foreground",children:["\xb7 ",e.rating,"/5"]})]}),(0,n.jsx)("span",{className:"text-xs text-muted-foreground",children:new Date(e.created_at).toLocaleStr
1ing()})]}),(0,n.jsx)("p",{className:"text-xs font-mono text-primary",children:(0,n.jsx)(i.N_,{to:"/admin/products/edit/".concat(encodeURIComponent(e.product_slug),"/"),className:"hover:underline",children:e.product_slug})}),(0,n.jsxs)("p",{className:"text-sm text-muted-foreground",children:[e.author_name||"Anonymous",e.author_email?" \xb7 ".concat(e.author_email):""]}),(0,n.jsx)("p",{className:"text-sm whitespace-pre-wrap",children:e.content}),(0,n.jsxs)("div",{className:"flex flex-wrap gap-2 pt-1",children:["approved"!==e.status?(0,n.jsx)(L.Button,{size:"sm",variant:"secondary",disabled:c.isPending,onClick:()=>c.mutate({id:e.id,patch:{status:"approved"}}),children:"Approve"}):null,"spam"!==e.status?(0,n.jsx)(L.Button,{size:"sm",variant:"outline",disabled:c.isPending,onClick:()=>c.mutate({id:e.id,patch:{status:"spam"}}),children:"Spam"}):null,"pending"!==e.status?(0,n.jsx)(L.Button,{size:"sm",variant:"outline",disabled:c.isPending,onClick:()=>c.mutate({id:e.id,patch:{status:"pending"}}),children:"Pending"}):null,(0,n.jsx)(L.Button,{size:"sm",variant:"destructive",disabled:u.isPending,onClick:()=>{window.confirm("Delete this review permanently?")&&u.mutate(e.id)},children:"Delete"})]})]},e.id))})})]})},{})}),(0,n.jsx)(s.qh,{path:"products/tags",element:(0,n.jsx)(function(){let e=(0,o.jE)(),{data:t=[],isLoading:r,error:s}=(0,eK.I)({queryKey:["admin","product_tags"],queryFn:a1}),{data:l={}}=(0,eK.I)({queryKey:["admin","product_tag_assignment_counts"],queryFn:a2,staleTime:3e4}),d=(0,a.useMemo)(()=>t.map(e=>({...e,_count:l[e.id]||0})),[t,l]),[c,u]=(0,a.useState)(""),[m,h]=(0,a.useState)(0),[p,g]=(0,a.useState)(""),[x,f]=(0,a.useState)(null),v=(0,tO.n)({mutationFn:async e=>{let{error:t}=await T.N.from("product_tags").insert(e);if(t)throw t},onSuccess:()=>{e.invalidateQueries({queryKey:["admin","product_tags"]}),e.invalidateQueries({queryKey:["admin","product_tag_assignment_counts"]}),u(""),g(""),h(0)}}),y=(0,tO.n)({mutationFn:async e=>{let{id:t,name:r,slug:n,description:a,sort_order:s}=e,{error:i}=await T.N.from("product_tags").update({name:r,slug:n,description:a,sort_order:s}).eq("id",t);if(i)throw i},onSuccess:()=>{e.invalidateQueries({queryKey:["admin","product_tags"]}),f(null)}}),b=(0,tO.n)({mutationFn:async e=>{let{error:t}=await T.N.from("product_tags").delete().eq("id",e.id);if(t)throw t},onSuccess:()=>{e.invalidateQueries({queryKey:["admin","product_tags"]}),e.invalidateQueries({queryKey:["admin","product_tag_assignment_counts"]})}});return(0,n.jsxs)("div",{className:"space-y-6",children:[(0,n.jsxs)("div",{children:[(0,n.jsxs)("p",{className:"text-sm text-muted-foreground mb-1",children:[(0,n.jsx)(i.N_,{to:"/admin/products/",className:"hover:underline",children:"Products"})," ","/ Tags"]}),(0,n.jsx)("h1",{className:"text-2xl font-semibold",children:"Product tags"}),(0,n.jsx)("p",{className:"text-sm text-muted-foreground mt-1",children:"Flat labels for products. Assign tags on each product edit screen."})]}),s?(0,n.jsxs)("div",{className:"rounded-lg border border-destructive/30 bg-destructive/10 px-3 py-2 text-sm text-destructive",children:[(0,n.jsx)("p",{children:s.message}),(0,n.jsxs)("p",{className:"text-xs mt-1",children:["Run ",(0,n.jsx)("code",{className:"rounded bg-background px-1",children:"scripts/ensure-product-extensions.sql"}),"."]})]}):null,(0,n.jsxs)("div",{className:"grid gap-6 lg:grid-cols-2",children:[(0,n.jsxs)("div",{className:"rounded-2xl border bg-card p-5 space-y-4 h-fit",children:[(0,n.jsx)("p",{className:"text-sm font-medium",children:"Add new tag"}),(0,n.jsxs)("div",{className:"grid gap-2",children:[(0,n.jsx)(tH,{htmlFor:"pt-name",children:"Name"}),(0,n.jsx)(tR.p,{id:"pt-name",value:c,onChange:e=>u(e.target.value),placeholder:"e.g. Organic"})]}),(0,n.jsxs)("div",{className:"grid gap-2",children:[(0,n.jsx)(tH,{htmlFor:"pt-desc",children:"Description (optional)"}),(0,n.jsx)(rP.T,{id:"pt-desc",value:p,onChange:e=>g(e.target.value),rows:3})]}),(0,n.jsxs)("div",{className:"grid gap-2 max-w-[120px]",children:[(0,n.jsx)(tH,{htmlFor:"pt-sort",children:"Sort"}),(0,n.jsx)(tR.p,{id:"pt-sort",type:"number",value:m,onChange:e=>h(Number(e.target.value)||0)})]}),(0,n.jsx)(L.Button,{type:"button",onClick:()=>{let e=c.trim();e&&v.mutate({name:e,slug:a0(e),description:p.trim()||null,sort_order:m})},disabled:v.isPending||!c.trim(),children:"Add tag"})]}),(0,n.jsxs)("div",{className:"rounded-2xl border bg-card overflow-hidden min-h-[200px]",children:[(0,n.jsxs)("div",{className:"grid grid-cols-[1fr_1fr_80px_100px] gap-2 border-b px-4 py-3 text-xs font-medium text-muted-foreground",children:[(0,n.jsx)("div",{children:"Name"}),(0,n.jsx)("div",{children:"Slug"}),(0,n.jsx)("div",{className:"text-right",children:"Count"}),(0,n.jsx)("div",{className:"text-right",children:"Actions"})]}),r?(0,n.jsx)("div",{className:"px-4 py-6 text-sm text-muted-foreground",children:"Loading…"}):d.length?(0,n.jsx)("div",{className:"divide-y max-h-[min(70vh,520px)] overflow-y-auto",children:d.map(e=>(0,n.jsxs)("div",{className:"grid grid-cols-[1fr_1fr_80px_100px] gap-2 items-center px-4 py-3",children:[(0,n.jsx)("div",{className:"text-sm font-medium truncate",children:e.name}),(0,n.jsx)("div",{className:"text-xs text-muted-foreground truncate font-mono",children:e.slug}),(0,n.jsx)("div",{className:"text-sm text-right tabular-nums",children:e._count}),(0,n.jsxs)("div",{className:"text-right flex justify-end gap-2",children:[(0,n.jsx)(L.Button,{type:"button",size:"sm",variant:"outline",onClick:()=>f(e),children:"Edit"}),(0,n.jsx)(L.Button,{type:"button",size:"sm",variant:"destructive",onClick:()=>{window.confirm("Delete tag “".concat(e.name,"”?"))&&b.mutate(e)},children:"Delete"})]})]},e.id))}):(0,n.jsx)("div",{className:"px-4 py-6 text-sm text-muted-foreground",children:"No tags yet."})]})]}),(0,n.jsx)(tQ,{open:!!x,onOpenChange:e=>!e&&f(null),children:(0,n.jsxs)(tX,{children:[(0,n.jsxs)(tZ,{children:[(0,n.jsx)(t1,{children:"Edit tag"}),(0,n.jsx)(t2,{children:"Update name, slug, or sort order."})]}),x?(0,n.jsx)(a4,{row:x,onCancel:()=>f(null),onSave:e=>y.mutateAsync({id:x.id,...e}).then(()=>f(null)),isSaving:y.isPending}):null]})})]})},{})}),(0,n.jsx)(s.qh,{path:"products/brands",element:(0,n.jsx)(function(){let e=(0,o.jE)(),{data:t=[],isLoading:r,error:s}=(0,eK.I)({queryKey:["admin","product_brands"],queryFn:a3}),{data:l={}}=(0,eK.I)({queryKey:["admin","product_brand_assignment_counts"],queryFn:a6,staleTime:3e4}),d=(0,a.useMemo)(()=>t.filter(e=>!e.parent_slug).map(e=>e.slug),[t]),c=(0,a.useMemo)(()=>t.map(e=>({...e,_count:l[e.id]||0})),[t,l]),[u,m]=(0,a.useState)(""),[h,p]=(0,a.useState)(""),[g,x]=(0,a.useState)(""),[f,v]=(0,a.useState)(""),[y,b]=(0,a.useState)(""),[j,w]=(0,a.useState)(0),[_,N]=(0,a.useState)(null),k=(0,tO.n)({mutationFn:async e=>{let{error:t}=await T.N.from("product_brands").insert(e);if(t)throw t},onSuccess:()=>
1{e.invalidateQueries({queryKey:["admin","product_brands"]}),m(""),p(""),x(""),v(""),b(""),w(0)}}),S=(0,tO.n)({mutationFn:async e=>{let{id:t,...r}=e,{error:n}=await T.N.from("product_brands").update(r).eq("id",t);if(n)throw n},onSuccess:()=>{e.invalidateQueries({queryKey:["admin","product_brands"]}),N(null)}}),C=(0,tO.n)({mutationFn:async e=>{let{error:t}=await T.N.from("product_brands").delete().eq("id",e.id);if(t)throw t},onSuccess:()=>{e.invalidateQueries({queryKey:["admin","product_brands"]}),e.invalidateQueries({queryKey:["admin","product_brand_assignment_counts"]})}});return(0,n.jsxs)("div",{className:"space-y-6",children:[(0,n.jsxs)("div",{children:[(0,n.jsxs)("p",{className:"text-sm text-muted-foreground mb-1",children:[(0,n.jsx)(i.N_,{to:"/admin/products/",className:"hover:underline",children:"Products"})," ","/ Brands"]}),(0,n.jsx)("h1",{className:"text-2xl font-semibold",children:"Product brands"}),(0,n.jsx)("p",{className:"text-sm text-muted-foreground mt-1",children:"Optional hierarchy via parent brand slug. Assign on each product edit screen."})]}),s?(0,n.jsxs)("div",{className:"rounded-lg border border-destructive/30 bg-destructive/10 px-3 py-2 text-sm text-destructive",children:[(0,n.jsx)("p",{children:s.message}),(0,n.jsxs)("p",{className:"text-xs mt-1",children:["Run ",(0,n.jsx)("code",{className:"rounded bg-background px-1",children:"scripts/ensure-product-extensions.sql"}),"."]})]}):null,(0,n.jsxs)("div",{className:"grid gap-6 lg:grid-cols-2",children:[(0,n.jsxs)("div",{className:"rounded-2xl border bg-card p-5 space-y-4 h-fit",children:[(0,n.jsx)("p",{className:"text-sm font-medium",children:"Add new brand"}),(0,n.jsxs)("div",{className:"grid gap-2",children:[(0,n.jsx)(tH,{htmlFor:"pb-name",children:"Name"}),(0,n.jsx)(tR.p,{id:"pb-name",value:u,onChange:e=>m(e.target.value)})]}),(0,n.jsxs)("div",{className:"grid gap-2",children:[(0,n.jsx)(tH,{htmlFor:"pb-slug",children:"Slug (optional)"}),(0,n.jsx)(tR.p,{id:"pb-slug",value:h,onChange:e=>p(e.target.value),className:"font-mono text-sm"})]}),(0,n.jsxs)("div",{className:"grid gap-2",children:[(0,n.jsx)(tH,{children:"Parent brand"}),(0,n.jsxs)(rl,{value:g||"__none__",onValueChange:e=>x("__none__"===e?"":e),children:[(0,n.jsx)(rd,{children:(0,n.jsx)(ro,{placeholder:"None"})}),(0,n.jsxs)(rm,{children:[(0,n.jsx)(rh,{value:"__none__",children:"None"}),d.map(e=>(0,n.jsx)(rh,{value:e,children:e},e))]})]})]}),(0,n.jsxs)("div",{className:"grid gap-2",children:[(0,n.jsx)(tH,{htmlFor:"pb-img",children:"Image URL (optional)"}),(0,n.jsx)(tR.p,{id:"pb-img",value:f,onChange:e=>v(e.target.value),placeholder:"https://…"})]}),(0,n.jsxs)("div",{className:"grid gap-2",children:[(0,n.jsx)(tH,{htmlFor:"pb-desc",children:"Description"}),(0,n.jsx)(rP.T,{id:"pb-desc",value:y,onChange:e=>b(e.target.value),rows:3})]}),(0,n.jsxs)("div",{className:"grid gap-2 max-w-[120px]",children:[(0,n.jsx)(tH,{htmlFor:"pb-sort",children:"Sort"}),(0,n.jsx)(tR.p,{id:"pb-sort",type:"number",value:j,onChange:e=>w(Number(e.target.value)||0)})]}),(0,n.jsx)(L.Button,{type:"button",onClick:()=>{let e=u.trim();if(!e)return;let t=h.trim()||a5(e);k.mutate({name:e,slug:t,parent_slug:g||null,image_url:f.trim()||null,description:y.trim()||null,sort_order:j})},disabled:k.isPending||!u.trim(),children:"Add brand"})]}),(0,n.jsxs)("div",{className:"rounded-2xl border bg-card overflow-hidden",children:[(0,n.jsxs)("div",{className:"grid grid-cols-[minmax(0,1fr)_minmax(0,1fr)_80px_100px] gap-2 border-b px-4 py-3 text-xs font-medium text-muted-foreground",children:[(0,n.jsx)("div",{children:"Name"}),(0,n.jsx)("div",{children:"Slug"}),(0,n.jsx)("div",{className:"text-right",children:"Count"}),(0,n.jsx)("div",{className:"text-right",children:"Actions"})]}),r?(0,n.jsx)("div",{className:"px-4 py-6 text-sm text-muted-foreground",children:"Loading…"}):c.length?(0,n.jsx)("div",{className:"divide-y max-h-[min(70vh,520px)] overflow-y-auto",children:c.map(e=>(0,n.jsxs)("div",{className:"grid grid-cols-[minmax(0,1fr)_minmax(0,1fr)_80px_100px] gap-2 items-center px-4 py-3",children:[(0,n.jsx)("div",{className:"text-sm font-medium truncate",children:e.name}),(0,n.jsx)("div",{className:"text-xs text-muted-foreground truncate font-mono",children:e.slug}),(0,n.jsx)("div",{className:"text-sm text-right tabular-nums",children:e._count}),(0,n.jsxs)("div",{className:"text-right flex justify-end gap-2 flex-wrap",children:[(0,n.jsx)(L.Button,{type:"button",size:"sm",variant:"outline",onClick:()=>N(e),children:"Edit"}),(0,n.jsx)(L.Button,{type:"button",size:"sm",variant:"destructive",onClick:()=>{window.confirm("Delete brand “".concat(e.name,"”?"))&&C.mutate(e)},children:"Delete"})]})]},e.id))}):(0,n.jsx)("div",{className:"px-4 py-6 text-sm text-muted-foreground",children:"No brands yet."})]})]}),(0,n.jsx)(tQ,{open:!!_,onOpenChange:e=>!e&&N(null),children:(0,n.jsxs)(tX,{className:"max-w-md",children:[(0,n.jsxs)(tZ,{children:[(0,n.jsx)(t1,{children:"Edit brand"}),(0,n.jsx)(t2,{children:"Update brand metadata."})]}),_?(0,n.jsx)(a8,{row:_,parentOptions:d.filter(e=>e!==_.slug),onCancel:()=>N(null),onSave:e=>S.mutateAsync({id:_.id,...e}).then(()=>N(null)),isSaving:S.isPending}):null]})})]})},{})}),(0,n.jsx)(s.qh,{path:"products/categories",element:(0,n.jsx)(function(){let e=(0,o.jE)(),{data:t,isLoading:r,error:s}=(0,eK.I)({queryKey:["admin","product_categories"],queryFn:a7}),[l,d]=(0,a.useState)(""),[c,u]=(0,a.useState)(""),[m,h]=(0,a.useState)(""),[p,g]=(0,a.useState)(0),[x,v]=(0,a.useState)(null),y=(0,a.useMemo)(()=>(t||[]).filter(e=>!e.parent_slug).map(e=>e.slug),[t]),b=(0,tO.n)({mutationFn:async e=>{let{data:t,error:r}=await T.N.from("product_categories").insert(e).select("*").single();if(r)throw r;return t},onSuccess:()=>
1{e.invalidateQueries({queryKey:["admin","product_categories"]}),d(""),u(""),h(""),g(0)},onError:e=>{f({title:"Could not add",description:(null==e?void 0:e.message)||"Unknown error",variant:"destructive"})}}),j=(0,tO.n)({mutationFn:async e=>{let{id:t,oldSlug:r,name:n,slug:a,parent_slug:s,sort_order:i}=e;r!==a&&await st(r,a);let{error:l}=await T.N.from("product_categories").update({name:n,slug:a,parent_slug:s||null,sort_order:i,updated_at:new Date().toISOString()}).eq("id",t);if(l)throw l},onSuccess:()=>{e.invalidateQueries({queryKey:["admin","product_categories"]}),e.invalidateQueries({queryKey:["admin","product_overrides"]}),e.invalidateQueries({queryKey:["public","product_overrides"]}),v(null)},onError:e=>{f({title:"Could not save",description:(null==e?void 0:e.message)||"Unknown error",variant:"destructive"})}}),w=(0,tO.n)({mutationFn:async e=>{let t=await se(e.slug);if(t>0)throw Error("".concat(t," product override(s) still use this slug. Change those products first, then delete."));let{error:r}=await T.N.from("product_categories").delete().eq("id",e.id);if(r)throw r},onSuccess:()=>{e.invalidateQueries({queryKey:["admin","product_categories"]})},onError:e=>{f({title:"Could not delete",description:(null==e?void 0:e.message)||"Unknown error",variant:"destructive"})}}),_=(0,tO.n)({mutationFn:async()=>{let e=new Set;Object.values(a9.oZ).forEach(t=>{t.parentCategorySlug&&e.add(t.parentCategorySlug),t.categorySlug&&e.add(t.categorySlug)});let{data:t}=await T.N.from("product_categories").select("slug"),r=new Set((t||[]).map(e=>e.slug)),{data:n}=await T.N.from("product_categories").select("sort_order"),a=(null==n?void 0:n.length)?Math.max(...n.map(e=>{var t;return null!=(t=e.sort_order)?t:0}),0):0;for(let t of e){if(r.has(t))continue;a+=1;let e=function(e){let t=String(e||"").split("/").filter(Boolean);return t.length<=1?null:t[0]}(t),{error:n}=await T.N.from("product_categories").insert({name:function(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:"";return e.split("/").pop().replace(/-/g," ").replace(/\b\w/g,e=>e.toUpperCase()).trim()}(t),slug:t,parent_slug:e,sort_order:a});if(n)throw n}},onSuccess:()=>e.invalidateQueries({queryKey:["admin","product_categories"]}),onError:e=>{f({title:"Sync failed",description:(null==e?void 0:e.message)||"Unknown error",variant:"destructive"})}}),N=t||[];return(0,n.jsxs)("div",{className:"space-y-6",children:[(0,n.jsxs)("div",{className:"flex flex-col gap-3 sm:flex-row sm:items-start sm:justify-between",children:[(0,n.jsxs)("div",{children:[(0,n.jsxs)("p",{className:"text-sm text-muted-foreground mb-1",children:[(0,n.jsx)(i.N_,{to:"/admin/products/",className:"hover:underline",children:"Products"})," ","/ Categories"]}),(0,n.jsx)("h1",{className:"text-2xl font-semibold",children:"Product categories"}),(0,n.jsxs)("p",{className:"text-sm text-muted-foreground mt-1",children:["Create and edit category slugs used with catalog products (parent and full category paths). Sync seeds rows from the static product catalog. The ",(0,n.jsx)("span",{className:"font-medium text-foreground",children:"Products"})," column counts items in the built-in catalog that match each slug (parent, exact category, or paths under it)."]})]}),(0,n.jsx)(L.Button,{type:"button",variant:"outline",onClick:()=>_.mutate(),disabled:_.isPending,children:_.isPending?"Syncing…":"Sync from catalog data"})]}),s?(0,n.jsxs)("div",{className:"rounded-lg border border-destructive/30 bg-destructive/10 px-3 py-2 text-sm text-destructive space-y-2",children:[(0,n.jsx)("p",{children:s.message}),(0,n.jsxs)("p",{className:"text-xs opacity-90",children:["If the table is missing, run ",(0,n.jsx)("code",{className:"rounded bg-background px-1",children:"scripts/ensure-product-categories.sql"})," in Supabase SQL Editor (after ",(0,n.jsx)("code",{className:"rounded bg-background px-1",children:"ensure-products.sql"}),")."]})]}):null,(0,n.jsxs)("div",{className:"rounded-2xl border bg-card p-5 space-y-4",children:[(0,n.jsx)("p",{className:"text-sm font-medium",children:"Add category"}),(0,n.jsxs)("div",{className:"grid gap-3 md:grid-cols-2",children:[(0,n.jsxs)("div",{className:"grid gap-2",children:[(0,n.jsx)(tH,{htmlFor:"pc-new-name",children:"Display name"}
1),(0,n.jsx)(tR.p,{id:"pc-new-name",value:l,onChange:e=>d(e.target.value),placeholder:"e.g. Men's Wear"})]}),(0,n.jsxs)("div",{className:"grid gap-2",children:[(0,n.jsx)(tH,{htmlFor:"pc-new-slug",children:"Slug (optional)"}),(0,n.jsx)(tR.p,{id:"pc-new-slug",value:c,onChange:e=>u(e.target.value),placeholder:"auto from name if empty",className:"font-mono text-sm"})]}),(0,n.jsxs)("div",{className:"grid gap-2 md:col-span-2 sm:max-w-xs",children:[(0,n.jsx)(tH,{children:"Parent category"}),(0,n.jsxs)(rl,{value:m||"__none__",onValueChange:e=>h("__none__"===e?"":e),children:[(0,n.jsx)(rd,{children:(0,n.jsx)(ro,{placeholder:"Top level"})}),(0,n.jsxs)(rm,{children:[(0,n.jsx)(rh,{value:"__none__",children:"Top level (no parent)"}),y.map(e=>(0,n.jsx)(rh,{value:e,children:e},e))]})]}),(0,n.jsxs)("p",{className:"text-xs text-muted-foreground",children:["For subcategories, full slug is usually ",(0,n.jsx)("span",{className:"font-mono",children:"parent/child"}),"."]})]}),(0,n.jsxs)("div",{className:"grid gap-2 sm:max-w-[140px]",children:[(0,n.jsx)(tH,{htmlFor:"pc-new-sort",children:"Sort"}),(0,n.jsx)(tR.p,{id:"pc-new-sort",type:"number",value:p,onChange:e=>g(Number(e.target.value)||0)})]})]}),(0,n.jsx)(L.Button,{type:"button",onClick:()=>{let e=l.trim();if(!e)return;let t=c.trim()||String(e||"").toLowerCase().trim().replace(/['"]/g,"").replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"");m&&!t.includes("/")&&(t="".concat(m,"/").concat(t)),b.mutate({name:e,slug:t,parent_slug:m||null,sort_order:p})},disabled:b.isPending||!l.trim(),children:"Add"})]}),(0,n.jsxs)("div",{className:"rounded-2xl border bg-card overflow-hidden",children:[(0,n.jsxs)("div",{className:"grid grid-cols-[minmax(0,1fr)_minmax(0,1fr)_minmax(0,5.5rem)_minmax(0,4.5rem)_4rem_9rem] gap-2 border-b px-4 py-3 text-xs font-medium text-muted-foreground items-center",children:[(0,n.jsx)("div",{children:"Name"}),(0,n.jsx)("div",{children:"Slug"}),(0,n.jsx)("div",{children:"Parent"}),(0,n.jsx)("div",{className:"text-right tabular-nums",children:"Products"}),(0,n.jsx)("div",{className:"text-right",children:"Sort"}),(0,n.jsx)("div",{className:"text-right",children:"Actions"})]}),r?(0,n.jsx)("div",{className:"px-4 py-6 text-sm text-muted-foreground",children:"Loading…"}):0===N.length?(0,n.jsx)("div",{className:"px-4 py-6 text-sm text-muted-foreground",children:"No categories yet. Add one or sync from catalog."}):(0,n.jsx)("div",{className:"divide-y",children:N.map(e=>(0,n.jsxs)("div",{className:"grid grid-cols-[minmax(0,1fr)_minmax(0,1fr)_minmax(0,5.5rem)_minmax(0,4.5rem)_4rem_9rem] gap-2 items-center px-4 py-3",children:[(0,n.jsx)("div",{className:"text-sm font-medium truncate",children:e.name}),(0,n.jsx)("div",{className:"text-xs text-muted-foreground truncate font-mono",children:e.slug}),(0,n.jsx)("div",{className:"text-xs text-muted-foreground truncate font-mono",children:e.parent_slug||"—"}),(0,n.jsx)("div",{className:"text-sm text-right tabular-nums font-medium text-foreground",children:function(e){if(!e)return 0;let t=0;for(let r of Object.values(a9.oZ)){let n=String(r.parentCategorySlug||"").trim(),a=String(r.categorySlug||"").trim();(n===e||a===e||a.startsWith("".concat(e,"/")))&&(t+=1)}return t}(e.slug)}),(0,n.jsx)("div",{className:"text-sm text-muted-foreground text-right tabular-nums",children:e.sort_order}),(0,n.jsxs)("div",{className:"text-right flex justify-end gap-2 flex-wrap",children:[(0,n.jsx)(L.Button,{type:"button",size:"sm",variant:"outline",onClick:()=>v(e),children:"Edit"}),(0,n.jsx)(L.Button,{type:"button",size:"sm",variant:"destructive",onClick:()=>{window.confirm("Delete “".concat(e.name,"”?"))&&w.mutate(e)},disabled:w.isPending,children:"Delete"})]})]},e.id))})]}),(0,n.jsx)(tQ,{open:!!x,onOpenChange:e=>!e&&v(null),children:(0,n.jsxs)(tX,{className:"max-w-lg",children:[(0,n.jsxs)(tZ,{children:[(0,n.jsx)(t1,{children:"Edit category"}),(0,n.jsxs)(t2,{children:["Changing the slug updates matching rows in the ",(0,n.jsx)("span",{className:"font-mono",children:"products"})," override table (parent and category paths)."]})]}),x?(0,n.jsx)(sr,{row:x,parentOptions:y.filter(e=>e!==x.slug),onCancel:()=>v(null),onSave:e=>j.mutateAsync({id:x.id,oldSlug:x.slug,name:e.name,slug:e.slug,parent_slug:e.parent_slug,sort_order:e.sort_order}).then(()=>v(null)),isSaving:j.isPending}):null]})})]})},{})}),(0,n.jsx)(s.qh,{path:"products/new",element:(0,n.jsx)(function(){let e=(0,s.Zp)(),t=(0,o.jE)(),[r,l]=(0,a.useState)(""),[d,c]=(0,a.useState)({title:"",image:"",description:"",short_description:"",price_range:"",moq:"",sku:"",stock_status:"instock",gallery_urls:"",parent_category_slug:"",category_slug:"",is_featured:!1,is_active:!0}),[u,m]=(0,a.useState)(""),h=String(r||"").trim().toLowerCase().replace(/\s+/g,"-").replace(/[^a-z0-9-]/g,"").replace(/-+/g,"-").replace(/^-|-$/g,""),p=h&&ss.includes(h),g=e=>t=>c(r=>({...r,[e]:"checkbox"===t.target.type?t.target.checked:t.target.value})),x=(0,tO.n)({mutationFn:async()=>{var e,t;if(!h)throw Error("Enter a URL slug (e.g. my-new-product).");let r=String(d.gallery_urls||"").split(/[\n,]+/).map(e=>
1e.trim()).filter(Boolean),{gallery_urls:n,...a}=d;await (0,sa.e6)(h,{...a,sku:(null==(e=a.sku)?void 0:e.trim())||null,short_description:(null==(t=a.short_description)?void 0:t.trim())||null,stock_status:a.stock_status||"instock",gallery_images:r})},onSuccess:()=>{t.invalidateQueries({queryKey:["admin","product_overrides"]}),t.invalidateQueries({queryKey:["public","product_override",h]}),t.invalidateQueries({queryKey:["public","product_overrides"]}),f({title:"Product saved",description:"Override stored for “".concat(h,"”.")}),e("/admin/products/")},onError:e=>m((null==e?void 0:e.message)||"Save failed")});return(0,n.jsxs)("div",{className:"w-full min-w-0 max-w-full space-y-6 pb-8",children:[(0,n.jsx)("div",{className:"flex flex-wrap items-center gap-3",children:(0,n.jsx)(L.Button,{type:"button",variant:"ghost",size:"sm",className:"gap-1.5 -ml-2",asChild:!0,children:(0,n.jsxs)(i.N_,{to:"/admin/products/",children:[(0,n.jsx)(sn.A,{className:"h-4 w-4"}),"All products"]})})}),(0,n.jsxs)("div",{children:[(0,n.jsxs)("h1",{className:"text-xl font-semibold flex items-center gap-2",children:[(0,n.jsx)(F.A,{className:"w-5 h-5"}),"Add new"]}),(0,n.jsx)("p",{className:"text-sm text-muted-foreground mt-1",children:"Creates a database entry for this slug. Catalog pages still list static products; new slugs get a generic template on the site until you fill in details below."})]}),(0,n.jsxs)("div",{className:"rounded-2xl border border-border bg-card p-6 shadow-sm space-y-4",children:[(0,n.jsxs)("div",{children:[(0,n.jsx)(tH,{htmlFor:"new-slug",children:"URL slug"}),(0,n.jsx)(tR.p,{id:"new-slug",value:r,onChange:e=>{l(e.target.value),m("")},placeholder:"e.g. organic-cotton-tee",className:"font-mono"}),(0,n.jsxs)("p",{className:"text-xs text-muted-foreground mt-1",children:["Used in ",(0,n.jsx)("span",{className:"font-mono",children:"/product/your-slug/"}),". Lowercase letters, numbers, and hyphens."]}),h?(0,n.jsxs)("p",{className:"text-xs mt-1 font-mono text-foreground",children:["Preview: ",(0,n.jsx)("span",{className:"text-primary",children:h})]}):null,p?(0,n.jsxs)("p",{className:"text-xs text-amber-700 dark:text-amber-400 mt-2",children:["This slug already exists in the catalog — saving will add or update its ",(0,n.jsx)("strong",{children:"override"})," only (same as Edit from the list)."]}):null]}),(0,n.jsxs)("div",{children:[(0,n.jsx)(tH,{htmlFor:"new-title",children:"Title"}),(0,n.jsx)(tR.p,{id:"new-title",value:d.title,onChange:g("title"),placeholder:"Product name"})]}),(0,n.jsxs)("div",{children:[(0,n.jsx)(tH,{htmlFor:"new-image",children:"Image URL"}),(0,n.jsx)(tR.p,{id:"new-image",value:d.image,onChange:g("image"),placeholder:"https://…"})]}),(0,n.jsxs)("div",{className:"grid gap-4 sm:grid-cols-2",children:[(0,n.jsxs)("div",{children:[(0,n.jsx)(tH,{htmlFor:"new-parent-cat",children:"Parent category slug"}),(0,n.jsx)(tR.p,{id:"new-parent-cat",value:d.parent_category_slug,onChange:g("parent_category_slug"),placeholder:"e.g. mens-wear",className:"font-mono text-sm"})]}),(0,n.jsxs)("div",{children:[(0,n.jsx)(tH,{htmlFor:"new-cat",children:"Category slug"}),(0,n.jsx)(tR.p,{id:"new-cat",value:d.category_slug,onChange:g("category_slug"),placeholder:"e.g. t-shirts",className:"font-mono text-sm"})]})]}),(0,n.jsxs)("div",{children:[(0,n.jsx)(tH,{htmlFor:"new-price",children:"Price range"}),(0,n.jsx)(tR.p,{id:"new-price",value:d.price_range,onChange:g("price_range"),placeholder:"e.g. $3.50 – $7.00 Ex-factory"})]}),(0,n.jsxs)("div",{children:[(0,n.jsx)(tH,{htmlFor:"new-moq",children:"MOQ"}),(0,n.jsx)(tR.p,{id:"new-moq",value:d.moq,onChange:g("moq"),placeholder:"e.g. 500 pcs per design"})]}),(0,n.jsxs)("div",{className:"grid gap-4 sm:grid-cols-2",children:[(0,n.jsxs)("div",{children:[(0,n.jsx)(tH,{htmlFor:"new-sku",children:"SKU"}),(0,n.jsx)(tR.p,{id:"new-sku",value:d.sku,onChange:g("sku"),placeholder:"Optional",className:"font-mono text-sm"})]}),(0,n.jsxs)("div",{children:[(0,n.jsx)(tH,{children:"Stock status"}),(0,n.jsxs)(rl,{value:d.stock_status,onValueChange:e=>c(t=>({...t,stock_status:e})),children:[(0,n.jsx)(rd,{id:"new-stock",className:"w-full",children:(0,n.jsx)(ro,{})}),(0,n.jsxs)(rm,{children:[(0,n.jsx)(rh,{value:"instock",children:"In stock"}),(0,n.jsx)(rh,{value:"outofstock",children:"Out of stock"}),(0,n.jsx)(rh,{value:"onbackorder",children:"On backorder"})]})]})]})]}),(0,n.jsxs)("div",{children:[(0,n.jsx)(tH,{htmlFor:"new-short-desc",children:"Short description"}),(0,n.jsx)(rP.T,{id:"new-short-desc",value:d.short_description,onChange:g("short_description"),rows:3,placeholder:"HTML snippet for above-the-fold summary…"})]}),(0,n.jsxs)("div",{children:[(0,n.jsx)(tH,{htmlFor:"new-desc",children:"Description"}),(0,n.jsx)(rP.T,{id:"new-desc",value:d.description,onChange:g("description"),rows:6,placeholder:"HTML or plain text…"})]}),(0,n.jsxs)("div",{children:[(0,n.jsx)(tH,{htmlFor:"new-gallery",children:"Gallery image URLs"}),(0,n.jsx)(rP.T,{id:"new-gallery",value:d.gallery_urls,onChange:g("gallery_urls"),rows:4,placeholder:"One URL per line (or comma-separated)",className:"font-mono text-sm"})]}),(0,n.jsxs)("div",{className:"flex flex-wrap gap-6",children:[(0,n.jsxs)("div",{className:"flex items-center gap-3",children:[(0,n.jsx)("input",{type:"checkbox",id:"new-featured",checked:d.is_featured,onChange:g("is_featured"),className:"h-4 w-4 roun
1ded border-input"}),(0,n.jsx)(tH,{htmlFor:"new-featured",className:"cursor-pointer",children:"Featured"})]}),(0,n.jsxs)("div",{className:"flex items-center gap-3",children:[(0,n.jsx)("input",{type:"checkbox",id:"new-active",checked:d.is_active,onChange:g("is_active"),className:"h-4 w-4 rounded border-input"}),(0,n.jsx)(tH,{htmlFor:"new-active",className:"cursor-pointer",children:"Active (visible on site)"})]})]}),h?(0,n.jsxs)("a",{href:"/product/".concat(h,"/"),target:"_blank",rel:"noopener noreferrer",className:"inline-flex items-center gap-1 text-sm text-primary hover:underline",children:["Open public product page ",(0,n.jsx)(rK.A,{className:"w-3.5 h-3.5"})]}):null,u?(0,n.jsx)("p",{className:"text-sm text-destructive",children:u}):null,(0,n.jsxs)("div",{className:"flex flex-wrap gap-2 pt-2",children:[(0,n.jsx)(L.Button,{type:"button",onClick:()=>x.mutate(),disabled:x.isPending||!h,children:x.isPending?"Saving…":"Save product"}),(0,n.jsx)(L.Button,{type:"button",variant:"outline",asChild:!0,children:(0,n.jsx)(i.N_,{to:"/admin/products/",children:"Cancel"})})]})]})]})},{})}),(0,n.jsx)(s.qh,{path:"products/edit/:slug",element:(0,n.jsx)(function(){let{slug:e}=(0,s.g)(),t=decodeURIComponent(e||"").replace(/\/$/,""),r=(0,s.Zp)(),l=(0,o.jE)(),d=(0,a.useMemo)(()=>({clipboard:{matchVisual:!1}}),[]),c=a9.oZ[t]||null,u=(null==c?void 0:c.title)||t;null==c||c.image;let m=(null==c?void 0:c.description)||"",[h,p]=(0,a.useState)(!0),[g,x]=(0,a.useState)({title:"",image:"",description:"",short_description:"",price_range:"",moq:"",sku:"",stock_status:"instock",category_slug:"",parent_category_slug:"",is_featured:!1,is_active:!0}),[v,y]=(0,a.useState)([]),[b,j]=(0,a.useState)([]),[w,_]=(0,a.useState)([]),[N,k]=(0,a.useState)(!1),[S,C]=(0,a.useState)(""),A=(0,a.useRef)(!1),{data:E=[]}=(0,eK.I)({queryKey:["admin","product_tags"],queryFn:si,staleTime:6e4}),{data:T=[]}=(0,eK.I)({queryKey:["admin","product_brands"],queryFn:sl,staleTime:6e4});(0,a.useEffect)(()=>{t&&(A.current||(A.current=!0,(async()=>{try{var e,r,n,a;let s=await (0,sa.dT)(t),i=null==s?void 0:s.gallery_images,l=Array.isArray(i)?i.filter(Boolean):"string"==typeof i?(()=>{try{let e=JSON.parse(i);return Array.isArray(e)?e:[]}catch(e){return[]}})():[];x({title:(null==s?void 0:s.title)||"",image:(null==s?void 0:s.image)||"",description:null!=(e=null==s?void 0:s.description)?e:"",short_description:null!=(r=null==s?void 0:s.short_description)?r:"",price_range:(null==s?void 0:s.price_range)||"",moq:(null==s?void 0:s.moq)||"",sku:(null==s?void 0:s.sku)||"",stock_status:(null==s?void 0:s.stock_status)||"instock",category_slug:(null==s?void 0:s.category_slug)||(null==c?void 0:c.categorySlug)||"",parent_category_slug:(null==s?void 0:s.parent_category_slug)||(null==c?void 0:c.parentCategorySlug)||"",is_featured:null!=(n=null==s?void 0:s.is_featured)&&n,is_active:null==(a=null==s?void 0:s.is_active)||a}),y(l.length?l:[]);let[o,d]=await Promise.all([(0,sa.RM)(t),(0,sa.GN)(t)]);j(o),_(d)}catch(e){x(e=>({...e,category_slug:(null==c?void 0:c.categorySlug)||"",parent_category_slug:(null==c?void 0:c.parentCategorySlug)||""})),f({title:"Partial load",description:(null==e?void 0:e.message)||"Some tables may be missing — run ensure-product-extensions.sql.",variant:"destructive"})}finally{p(!1)}})()))},[t,c]);let q=e=>t=>x(r=>({...r,[e]:"checkbox"===t.target.type?t.target.checked:t.target.value})),M=(0,tO.n)({mutationFn:async()=>{let e={title:g.title||null,image:g.image||null,description:g.description||null,short_description:g.short_description||null,price_range:g.price_range||null,moq:g.moq||null,sku:g.sku||null,stock_status:g.stock_status||"instock",category_slug:g.category_slug||null,parent_category_slug:g.parent_category_slug||null,is_featured:g.is_featured,is_active:g.is_active,gallery_images:v.filter(Boolean)};await (0,sa.e6)(t,e),await (0,sa.LB)(t,b),await (0,sa.K$)(t,w)},onSuccess:()=>{l.invalidateQueries({queryKey:["admin","product_overrides"]}),l.invalidateQueries({queryKey:["public","product_override",t]}),l.invalidateQueries({queryKey:["public","product_overrides"]}),f({title:"Saved",description:t}),r("/admin/products/")},onError:e=>C((null==e?void 0:e.message)||"Save failed")}),P=(0,a.useCallback)(e=>{let t=window.prompt("Image URL");if(!(null==t?void 0:t.trim()))return;let r=e.getSelection(!0),n=r?r.index:e.getLength();e.insertEmbed(n,"image",t.trim(),"user"),e.setSelection(n+1,0,"silent")},[]);return t?h?(0,n.jsx)("div",{className:"flex items-center justify-center py-24 text-muted-foreground text-sm",children:"Loading product…"}):(0,n.jsxs)("div",{className:"w-full min-w-0 max-w-full space-y-6 pb-16",children:[(0,n.jsx)("div",{className:"flex flex-wrap items-center gap-3",children:(0,n.jsx)(L.Button,{type:"button",variant:"ghost",size:"sm",className:"gap-1.5 -ml-2",asChild:!0,children:(0,n.jsxs)(i.N_,{to:"/admin/products/",children:[(0,n.jsx)(sn.A,{className:"h-4 w-4"}),"All products"]})})}),(0,n.jsxs)("div",{className:"flex flex-wrap items-start justify-between gap-4",children:[(0,n.jsxs)("div",{children:[(0,n.jsxs)("h1",{className:"text-xl font-semibold flex items-center gap-2",children:[(0,n.jsx)(F.A,{className:"w-5 h-5"}),"Edit product"]}),(0,n.jsx)("p",{className:"text-sm font-mono text-muted-foreground mt-1",children:t}),c?null:(0,n.jsx)("p",{className:"text-xs text-amber-700 dark:text-amber-400 mt-2",children:"This slug is not in the static catalog — DB-only override."})]}),(0,n.jsx)(L.Button,{variant:"outline",size:"sm",asChild:!0,children:(0,n.jsxs)("a",{href:"/product/".concat(t,"/"),target:"_blank",rel:"noopener noreferrer",className:"gap-1.5",children:["View live ",(0,n.jsx)(rK.A,{className:"h-3.5 w-3.5"})]})})]}),(0,n.jsxs)(t9,{defaultValue:"content",className:"w-full",children:[(0,n.jsxs)(t7,{className:"flex flex-wrap h-auto gap-1",children:[(0,n.jsx)(re,{value:"content",children:"Content"}),(0,n.jsx)(re,{value:"pricing",children:"Pricing and inventory"}),(0,n.jsx)(re,{value:"taxonomy",children:"Categories, tags, brands"}),(0,n.jsx)(re,{value:"visibility",children:"Visibility"})]}),(0,n.jsxs)(rt,{value:"content",className:"space-y-6 pt-4",children:[(0,n.jsxs)("div",{className:"grid gap-2 w-full min-w-0 max-w-full",children:[(0,n.jsx)(tH,{htmlFor:"pe-title",children:"Title"}),(0,n.jsx)(tR.p,{id:"pe-title",value:g.title,onChange:q("title"),placeholder:u})]}),(0,n.jsxs)("div",{className:"grid gap-2",children:[(0,n.jsx)(tH,{children:"Featured image"}),(0,n.jsx)(rF,{label:"Upload",value:g.image||"",onChange:e=>x(t=>({...t,image:e})),useMediaPicker:!0,mediaPickerTitle:"Product image",mediaPickerConfirmLabel:"Use image"}),(0,n.jsx)("p",{className:"text-xs text-muted-foreground",children:"Leave empty to use catalog default."})]}),(0,n.jsxs)("div",{className:"grid gap-2",children:[(0,n.jsx)(tH,{children:"Short description"}),(0,n.jsx)("div",{className:"rounded-md border border-border bg-background min-h-[140px]",children:(0,n.jsx)(ah,{value:g.short_description||"",onChange:e=>x(t=>({...t,short_description:e})),modules:d,placeholder:"Summary for cards…",onRequestImage:P})})]}),(0,n.jsxs)("div",{className:"grid gap-2",children:[(0,n.jsx)(tH,{children:"Full description"}),(0,n.jsx)("div",{className:"rounded-md border border-border bg-background min-h-[280px]",children:(0,n.jsx)(ah,{value:g.de
1scription||"",onChange:e=>x(t=>({...t,description:e})),modules:d,placeholder:m?"Override catalog HTML…":"Product description…",onRequestImage:P})})]}),(0,n.jsxs)("div",{className:"space-y-3",children:[(0,n.jsxs)("div",{className:"flex items-center justify-between gap-2",children:[(0,n.jsx)(tH,{children:"Gallery images"}),(0,n.jsxs)("div",{className:"flex gap-2",children:[(0,n.jsx)(L.Button,{type:"button",variant:"outline",size:"sm",onClick:()=>k(!0),children:"Add from media"}),(0,n.jsxs)(L.Button,{type:"button",variant:"outline",size:"sm",onClick:()=>y(e=>[...e,""]),className:"gap-1",children:[(0,n.jsx)(af.A,{className:"h-3.5 w-3.5"})," URL row"]})]})]}),(0,n.jsx)(rB,{open:N,onOpenChange:k,title:"Add gallery image",confirmLabel:"Add to gallery",onConfirm:e=>{y(t=>[...t,e]),k(!1)}}),(0,n.jsx)("ul",{className:"space-y-2",children:v.map((e,t)=>(0,n.jsxs)("li",{className:"flex gap-2 items-center",children:[(0,n.jsx)(tR.p,{value:e,onChange:e=>y(r=>r.map((r,n)=>n===t?e.target.value:r)),placeholder:"https://…",className:"font-mono text-sm"}),(0,n.jsx)(L.Button,{type:"button",variant:"ghost",size:"icon",onClick:()=>y(e=>e.filter((e,r)=>r!==t)),children:(0,n.jsx)(rW.A,{className:"h-4 w-4 text-destructive"})})]},t))})]})]}),(0,n.jsxs)(rt,{value:"pricing",className:"space-y-4 pt-4 w-full min-w-0 max-w-full",children:[(0,n.jsxs)("div",{className:"grid gap-2",children:[(0,n.jsx)(tH,{htmlFor:"pe-price",children:"Price range"}),(0,n.jsx)(tR.p,{id:"pe-price",value:g.price_range,onChange:q("price_range"),placeholder:"e.g. $3.50 – $7.00 Ex-factory"})]}),(0,n.jsxs)("div",{className:"grid gap-2",children:[(0,n.jsx)(tH,{htmlFor:"pe-moq",children:"MOQ"}),(0,n.jsx)(tR.p,{id:"pe-moq",value:g.moq,onChange:q("moq"),placeholder:"e.g. 500 pcs"})]}),(0,n.jsxs)("div",{className:"grid gap-2",children:[(0,n.jsx)(tH,{htmlFor:"pe-sku",children:"SKU"}),(0,n.jsx)(tR.p,{id:"pe-sku",value:g.sku,onChange:q("sku"),placeholder:"Stock keeping unit",className:"font-mono text-sm"})]}),(0,n.jsxs)("div",{className:"grid gap-2",children:[(0,n.jsx)(tH,{children:"Stock status"}),(0,n.jsxs)(rl,{value:g.stock_status,onValueChange:e=>x(t=>({...t,stock_status:e})),children:[(0,n.jsx)(rd,{className:"w-full max-w-full sm:max-w-md",children:(0,n.jsx)(ro,{})}),(0,n.jsxs)(rm,{children:[(0,n.jsx)(rh,{value:"instock",children:"In stock"}),(0,n.jsx)(rh,{value:"outofstock",children:"Out of stock"}),(0,n.jsx)(rh,{value:"onbackorder",children:"On backorder"})]})]})]})]}),(0,n.jsxs)(rt,{value:"taxonomy",className:"space-y-4 pt-4 w-full min-w-0 max-w-full",children:[(0,n.jsxs)("p",{className:"text-sm text-muted-foreground",children:["Category slugs should match"," ",(0,n.jsx)(i.N_,{to:"/admin/products/categories/",className:"text-primary hover:underline",children:"Products → Categories"}),"."]}),(0,n.jsxs)("div",{className:"grid gap-2",children:[(0,n.jsx)(tH,{htmlFor:"pe-pcat",children:"Parent category slug"}),(0,n.jsx)(tR.p,{id:"pe-pcat",value:g.parent_category_slug,onChange:q("parent_category_slug"),className:"font-mono text-sm",placeholder:"e.g. mens-wear"})]}),(0,n.jsxs)("div",{className:"grid gap-2",children:[(0,n.jsx)(tH,{htmlFor:"pe-cat",children:"Category slug"}),(0,n.jsx)(tR.p,{id:"pe-cat",value:g.category_slug,onChange:q("category_slug"),className:"font-mono text-sm",placeholder:"e.g. mens-wear/t-shirts"})]}),(0,n.jsxs)("div",{className:"grid gap-2",children:[(0,n.jsx)(tH,{children:"Tags"}),(0,n.jsx)("div",{className:"rounded-lg border border-border p-3 max-h-48 overflow-y-auto space-y-2",children:0===E.length?(0,n.jsx)("p",{className:"text-xs text-muted-foreground",children:"No tags yet — add under Products → Tags."}):E.map(e=>(0,n.jsxs)("label",{className:"flex items-center gap-2 text-sm cursor-pointer",children:[(0,n.jsx)(ra,{checked:b.includes(e.id),onCheckedChange:t=>{j(r=>t?[...r,e.id]:r.filter(t=>t!==e.id))}}),(0,n.jsx)("span",{children:e.name}),(0,n.jsx)("span",{className:"text-xs text-muted-foreground font-mono",children:e.slug})]},e.id))})]}),(0,n.jsxs)("div",{className:"grid gap-2",children:[(0,n.jsx)(tH,{children:"Brands"}),(0,n.jsx)("div",{className:"rounded-lg border border-border p-3 max-h-48 overflow-y-auto space-y-2",children:0===T.length?(0,n.jsx)("p",{className:"text-xs text-muted-foreground",children:"No brands yet — add under Products → Brands."}):T.map(e=>(0,n.jsxs)("label",{className:"flex items-center gap-2 text-sm cursor-pointer",children:[(0,n.jsx)(ra,{checked:w.includes(e.id),onCheckedChange:t=>{_(r=>t?[...r,e.id]:r.filter(t=>t!==e.id))}}),(0,n.jsx)("span",{children:e.name}),(0,n.jsx)("span",{className:"text-xs text-muted-foreground font-mono",children:e.slug})]},e.id))})]})]}),(0,n.jsxs)(rt,{value:"visibility",className:"space-y-4 pt-4",children:[(0,n.jsxs)("label",{className:"flex items-center gap-3",children:[(0,n.jsx)(ra,{checked:g.is_featured,onCheckedChange:e=>x(t=>({...t,is_featured:!!e}))}),(0,n.jsx)("span",{className:"text-sm",children:"Featured product"})]}),(0,n.jsxs)("label",{className:"flex items-center gap-3",children:[(0,n.jsx)(ra,{checked:g.is_active,onCheckedChange:e=>x(t=>({...t,is_active:!!e}))}),(0,n.jsx)("span",{className:"text-sm",children:"Active (visible on site)"})]})]})]}),S?(0,n.jsx)("p",{className:"text-sm text-destructive",children:S}):null,(0,n.jsxs)("div",{className:"flex flex-wrap gap-2 pt-2 border-t",children:[(0,n.jsx)(L.Button,{type:"button",onClick:()=>M.mutate(),disabled:M.isPending,children:M.isPending?"Saving…":"Save product"}),(0,n.jsx)(L.Button,{type:"button",variant:"outline",asChild:!0,children:(0,n.jsx)(i.N_,{to:"/admin/products/",children:"Cancel"})})]})]}):(0,n.jsxs)("div",{className:"p-6",children:[(0,n.jsx)("p",{className:"text-muted-foreground",children:"Invalid product."}),(0,n.jsx)(L.Button,{asChild:!0,variant:"link",className:"mt-2",children:(0,n.jsx)(i.N_,{to:"/admin/products/",children:"Back to products"})})]})},{})}),(0,n.jsx)(s.qh,{path:"products",element:(0,n.jsx)(function(){let[e,t]=(0,a.useState)(""),[r,s]=(0,a.useState)("All"),[l,d]=(0,a.useState)(0),[c,u]=(0,a.useState)(()=>new Set),m=(0,o.jE)(),{data:h={}}=(0,eK.I)({queryKey:["admin","product_overrides"],queryFn:su}),{data:p=[]}=(0,eK.I)({queryKey:["admin","product_categories","filter-options"],queryFn:sm,staleTime:6e4}),g=(0,a.useMemo)(()=>[...new Set([...p.map(e=>
1e.slug).filter(Boolean),...new Set(sc.map(e=>e.parentCategorySlug||e.categorySlug).filter(Boolean))])].sort((e,t)=>e.localeCompare(t)),[p]),x=(0,a.useMemo)(()=>{let t=e.toLowerCase();return sc.filter(n=>{let a=h[n.slug],s=function(e,t,r){if(!r||"All"===r)return!0;let{parent:n,category:a}=sd(e,t);return n===r||a===r||a.startsWith("".concat(r,"/"))}(n,a,r),i=!e||n.slug.includes(t)||(n.title||"").toLowerCase().includes(t);return s&&i})},[e,r,h]),v=Math.ceil(x.length/40),b=x.slice(40*l,40*l+40),j=(0,a.useRef)(e),w=(0,a.useRef)(r);(j.current!==e||w.current!==r)&&(j.current=e,w.current=r,0!==l&&d(0));let _=(0,tO.n)({mutationFn:async e=>{var t;let{slugs:r,patch:n}=e,a=new Date().toISOString(),{data:s,error:i}=await T.N.from("products").update({...n,updated_at:a}).in("slug",r).select("slug");if(i)throw i;return null!=(t=null==s?void 0:s.length)?t:0},onSuccess:(e,t)=>{m.invalidateQueries({queryKey:["admin","product_overrides"]}),m.invalidateQueries({queryKey:["public","product_overrides"]}),u(new Set),f({title:"Updated",description:"".concat(e," product row(s) in database.")})},onError:e=>f({title:"Bulk update failed",description:null==e?void 0:e.message,variant:"destructive"})}),N=b.map(e=>e.slug),k=N.length>0&&N.every(e=>c.has(e)),S=N.some(e=>c.has(e)),C=[...c];return(0,n.jsxs)("div",{className:"flex flex-col h-full min-h-0",children:[(0,n.jsxs)("div",{className:"shrink-0 border-b border-border bg-background px-6 py-4",children:[(0,n.jsxs)("div",{className:"flex flex-wrap items-center justify-between gap-4",children:[(0,n.jsxs)("div",{children:[(0,n.jsxs)("h1",{className:"text-xl font-semibold flex items-center gap-2",children:[(0,n.jsx)(F.A,{className:"w-5 h-5"}),"Products"]}),(0,n.jsxs)("p",{className:"text-sm text-muted-foreground mt-0.5",children:[sc.length," products \xb7 ",Object.keys(h).length," with DB overrides"]})]}),(0,n.jsx)(L.Button,{asChild:!0,size:"sm",children:(0,n.jsx)(i.N_,{to:"/admin/products/new/",children:"Add new"})})]}),(0,n.jsxs)("div",{className:"mt-4 flex flex-wrap gap-3 items-center",children:[(0,n.jsxs)("div",{className:"relative flex-1 min-w-[200px] max-w-xs",children:[(0,n.jsx)(tF.A,{className:"absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-muted-foreground"}),(0,n.jsx)(tR.p,{value:e,onChange:e=>t(e.target.value),placeholder:"Search title or slug…",className:"pl-9"}),e&&(0,n.jsx)("button",{type:"button",onClick:()=>t(""),className:"absolute right-3 top-1/2 -translate-y-1/2 text-muted-foreground hover:text-foreground",children:(0,n.jsx)(y.A,{className:"w-4 h-4"})})]}),(0,n.jsxs)("select",{value:r,onChange:e=>s(e.target.value),className:"h-9 rounded-md border border-input bg-background px-3 text-sm min-w-[180px]",children:[(0,n.jsx)("option",{value:"All",children:"All categories"}),g.map(e=>(0,n.jsx)("option",{value:e,children:function(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:"";return e.replace(/-/g," ").replace(/\b\w/g,e=>e.toUpperCase())}(e)},e))]}),(0,n.jsxs)("span",{className:"text-sm text-muted-foreground",children:[x.length," result",1!==x.length?"s":""]})]}),C.length>0?(0,n.jsxs)("div",{className:"mt-4 flex flex-wrap items-center gap-2 rounded-lg border border-border bg-muted/30 px-3 py-2 text-sm",children:[(0,n.jsxs)("span",{className:"text-muted-foreground",children:[C.length," selected"]}),(0,n.jsx)(L.Button,{type:"button",size:"sm",variant:"secondary",disabled:_.isPending,onClick:()=>_.mutate({slugs:C,patch:{is_featured:!0}}),children:"Mark featured"}),(0,n.jsx)(L.Button,{type:"button",size:"sm",variant:"secondary",disabled:_.isPending,onClick:()=>_.mutate({slugs:C,patch:{is_featured:!1}}),children:"Unfeature"}),(0,n.jsx)(L.Button,{type:"button",size:"sm",variant:"secondary",disabled:_.isPending,onClick:()=>_.mutate({slugs:C,patch:{is_active:!0}}),children:"Activate"}),(0,n.jsx)(L.Button,{type:"button",size:"sm",variant:"secondary",disabled:_.isPending,onClick:()=>_.mutate({slugs:C,patch:{is_active:!1}}),children:"Deactivate"}),(0,n.jsx)(L.Button,{type:"button",size:"sm",variant:"ghost",onClick:()=>u(new Set),children:"Clear selection"})]}):null]}),(0,n.jsxs)("div",{className:"flex-1 overflow-y-auto overflow-x-auto",children:[(0,n.jsxs)("table",{className:"w-full text-sm min-w-[720px]",children:[(0,n.jsx)("thead",{className:"sticky top-0 bg-muted/80 backdrop-blur border-b border-border z-10",children:(0,n.jsxs)("tr",{children:[(0,n.jsx)("th",{className:"w-10 px-2 py-2 text-left",children:(0,n.jsx)(ra,{checked:!!k||!!S&&"indeterminate",onCheckedChange:()=>void u(e=>{let t=new Set(e);
1return k?N.forEach(e=>t.delete(e)):N.forEach(e=>t.add(e)),t}),"aria-label":"Select all on this page"})}),(0,n.jsx)("th",{className:"text-left px-2 py-2 font-medium text-muted-foreground w-14",children:"Image"}),(0,n.jsx)("th",{className:"text-left px-2 py-2 font-medium text-muted-foreground",children:"Product"}),(0,n.jsx)("th",{className:"text-left px-2 py-2 font-medium text-muted-foreground hidden lg:table-cell",children:"Category"}),(0,n.jsx)("th",{className:"text-left px-2 py-2 font-medium text-muted-foreground hidden xl:table-cell w-28",children:"SKU"}),(0,n.jsx)("th",{className:"text-left px-2 py-2 font-medium text-muted-foreground hidden xl:table-cell w-28",children:"Stock"}),(0,n.jsx)("th",{className:"text-left px-2 py-2 font-medium text-muted-foreground hidden md:table-cell",children:"Status"}),(0,n.jsx)("th",{className:"px-2 py-2 w-28"})]})}),(0,n.jsx)("tbody",{className:"divide-y divide-border",children:b.map(e=>{let t=h[e.slug],r=(null==t?void 0:t.image)||e.image,a=(null==t?void 0:t.title)||e.title||e.slug,{parent:s,category:l}=sd(e,t),o=[s,l].filter(Boolean).join(" / "),d=(null==t?void 0:t.sku)||"—",m=(null==t?void 0:t.stock_status)?({instock:"In stock",outofstock:"Out of stock",onbackorder:"On backorder"})[t.stock_status]||t.stock_status:"—";return(0,n.jsxs)("tr",{className:"hover:bg-muted/30 transition-colors",children:[(0,n.jsx)("td",{className:"px-2 py-2",children:(0,n.jsx)(ra,{checked:c.has(e.slug),onCheckedChange:()=>{var t;return t=e.slug,void u(e=>{let r=new Set(e);return r.has(t)?r.delete(t):r.add(t),r})},"aria-label":"Select ".concat(e.slug)})}),(0,n.jsx)("td",{className:"px-2 py-2",children:(0,n.jsx)("img",{src:r,alt:a,className:"w-10 h-12 object-cover rounded border border-border"})}),(0,n.jsxs)("td",{className:"px-2 py-2",children:[(0,n.jsx)("p",{className:"font-medium line-clamp-1",children:a}),(0,n.jsx)("p",{className:"text-xs text-muted-foreground font-mono",children:e.slug}),(0,n.jsxs)("a",{href:"/product/".concat(e.slug,"/"),target:"_blank",rel:"noopener noreferrer",className:"text-xs text-primary hover:underline inline-flex items-center gap-0.5 mt-0.5",children:["View ",(0,n.jsx)(rK.A,{className:"w-3 h-3"})]})]}),(0,n.jsx)("td",{className:"px-2 py-2 hidden lg:table-cell text-muted-foreground text-xs max-w-[200px]",children:(0,n.jsx)("span",{className:"line-clamp-2",children:o||"—"})}),(0,n.jsx)("td",{className:"px-2 py-2 hidden xl:table-cell font-mono text-xs text-muted-foreground",children:d}),(0,n.jsx)("td",{className:"px-2 py-2 hidden xl:table-cell text-xs capitalize text-muted-foreground",children:m}),(0,n.jsx)("td",{className:"px-2 py-2 hidden md:table-cell",children:(0,n.jsxs)("div",{className:"flex flex-wrap gap-1",children:[t?(0,n.jsx)(tB,{variant:"default",className:"text-xs",children:"Edited"}):(0,n.jsx)(tB,{variant:"outline",className:"text-xs text-muted-foreground",children:"Default"}),(null==t?void 0:t.is_featured)&&(0,n.jsxs)(tB,{variant:"secondary",className:"text-xs gap-1",children:[(0,n.jsx)(so.A,{className:"w-3 h-3"}),"Featured"]}),t&&!1===t.is_active?(0,n.jsx)(tB,{variant:"destructive",className:"text-xs",children:"Hidden"}):null]})}),(0,n.jsx)("td",{className:"px-2 py-2 text-right",children:(0,n.jsx)(L.Button,{size:"sm",variant:"outline",asChild:!0,className:"gap-1.5",children:(0,n.jsxs)(i.N_,{to:"/admin/products/edit/".concat(encodeURIComponent(e.slug),"/"),children:[(0,n.jsx)(rO.A,{className:"w-3 h-3"}),"Edit"]})})})]},e.slug)})})]}),0===x.length&&(0,n.jsxs)("div",{className:"text-center py-16 text-muted-foreground",children:[(0,n.jsx)(F.A,{className:"w-10 h-10 mx-auto mb-3 opacity-30"}),(0,n.jsx)("p",{children:"No products found for this filter."})]})]}),v>1&&(0,n.jsxs)("div",{className:"shrink-0 border-t border-border px-6 py-3 flex items-center justify-between gap-4",children:[(0,n.jsxs)("p",{className:"text-sm text-muted-foreground",children:["Page ",l+1," of ",v," \xb7 showing ",b.length," of ",x.length]}),(0,n.jsxs)("div",{className:"flex gap-2",children:[(0,n.jsx)(L.Button,{size:"sm",variant:"outline",onClick:()=>d(e=>e-1),disabled:0===l,children:"Previous"}),(0,n.jsx)(L.Button,{size:"sm",variant:"outline",onClick:()=>d(e=>e+1),disabled:l>=v-1,children:"Next"})]})]})]})},{})}),(0,n.jsx)(s.qh,{path:"seo/overview",element:(0,n.jsx)(function(){let{data:e,isLoading:t}=(0,eK.I)({queryKey:["admin","seo_overview"],queryFn:sg,staleTime:6e4});return(0,n.jsxs)("div",{className:"space-y-8",children:[(0,n.jsxs)("div",{children:[(0,n.jsx)("h1",{className:"text-2xl font-semibold",children:"Appar SEO"}),(0,n.jsx)("p",{className:"text-sm text-muted-foreground mt-1",children:"Manage all on-site SEO settings — pages, redirects, and site verification."})]}),(0,n.jsx)("div",{className:"grid gap-4 sm:grid-cols-2 lg:grid-cols-3",children:sx.map(r=>{var a;let s=r.icon,l="function"==typeof r.countLabel?r.countLabel(null!=e?e:{verificationCount:0,verificationTotal:7}):"".concat(t?"—":null!=(a=null==e?void 0:e[r.countKey])?a:0," ").concat(r.countLabel);return(0,n.jsxs)(i.N_,{to:r.path,className:"group relative flex flex-col gap-4 roun
1ded-2xl border bg-card p-5 shadow-sm transition-shadow hover:shadow-md",children:[(0,n.jsxs)("div",{className:"flex items-start justify-between",children:[(0,n.jsx)("div",{className:"flex h-10 w-10 items-center justify-center rounded-xl bg-primary/10 text-primary",children:(0,n.jsx)(s,{className:"h-5 w-5"})}),(0,n.jsx)(rK.A,{className:"h-4 w-4 text-muted-foreground opacity-0 transition-opacity group-hover:opacity-100"})]}),(0,n.jsxs)("div",{children:[(0,n.jsx)("p",{className:"font-semibold",children:r.label}),(0,n.jsx)("p",{className:"mt-1 text-sm text-muted-foreground leading-relaxed",children:r.description})]}),(0,n.jsx)("p",{className:"text-xs font-medium text-primary",children:t?"—":l})]},r.path)})}),(0,n.jsxs)("div",{className:"rounded-2xl border bg-card p-5 space-y-3",children:[(0,n.jsx)("p",{className:"text-sm font-semibold",children:"Quick links"}),(0,n.jsxs)("div",{className:"flex flex-wrap gap-2 text-sm",children:[(0,n.jsxs)("a",{href:"/sitemap.xml",target:"_blank",rel:"noopener noreferrer",className:"inline-flex items-center gap-1 rounded-lg border px-3 py-1.5 text-muted-foreground hover:text-foreground hover:bg-muted transition-colors",children:["sitemap.xml ",(0,n.jsx)(rK.A,{className:"h-3 w-3"})]}),(0,n.jsxs)("a",{href:"/robots.txt",target:"_blank",rel:"noopener noreferrer",className:"inline-flex items-center gap-1 rounded-lg border px-3 py-1.5 text-muted-foreground hover:text-foreground hover:bg-muted transition-colors",children:["robots.txt ",(0,n.jsx)(rK.A,{className:"h-3 w-3"})]}),(0,n.jsx)(i.N_,{to:"/admin/settings/general/",className:"inline-flex items-center gap-1 rounded-lg border px-3 py-1.5 text-muted-foreground hover:text-foreground hover:bg-muted transition-colors",children:"Settings (General)"}),(0,n.jsx)(i.N_,{to:"/admin/auto-linking/",className:"inline-flex items-center gap-1 rounded-lg border px-3 py-1.5 text-muted-foreground hover:text-foreground hover:bg-muted transition-colors",children:"Auto Linking"}),(0,n.jsx)(i.N_,{to:"/admin/seo/verification/#admin-google-analytics",className:"inline-flex items-center gap-1 rounded-lg border px-3 py-1.5 text-muted-foreground hover:text-foreground hover:bg-muted transition-colors",children:"Google Analytics (GA4)"})]})]})]})},{})}),(0,n.jsx)(s.qh,{path:"seo/verification",element:(0,n.jsx)(function(){var e;let t=(0,o.jE)(),{hash:r}=(0,s.zy)(),{data:i,isLoading:l}=(0,eK.I)({queryKey:["admin","seo_verification"],queryFn:sy}),[d,c]=(0,a.useState)(sb),[u,m]=(0,a.useState)(!1),[h,p]=(0,a.useState)("");(0,a.useEffect)(()=>{i&&c({...Object.fromEntries(sf.map(e=>[e.key,i[e.key]||""])),google_analytics_measurement_id:i.google_analytics_measurement_id||""})},[i]),(0,a.useEffect)(()=>{l||"admin-google-analytics"===String(r||"").replace(/^#/,"")&&requestAnimationFrame(()=>{var e;null==(e=document.getElementById("admin-google-analytics"))||e.scrollIntoView({behavior:"smooth",block:"start"})})},[r,l]);let g=(0,tO.n)({mutationFn:async e=>{let{error:t}=await T.N.from("site_settings").update({...e,updated_at:new Date().toISOString()}).eq("id",1);if(t)throw t},onSuccess:()=>{t.invalidateQueries({queryKey:["admin","seo_verification"]}),t.invalidateQueries({queryKey:["public","site_verification"]}),t.invalidateQueries({queryKey:["public","google_analytics"]}),m(!0),setTimeout(()=>m(!1),3e3)}});return(0,n.jsxs)("div",{className:"space-y-6 max-w-2xl",children:[(0,n.jsxs)("div",{children:[(0,n.jsx)("h1",{className:"text-2xl font-semibold",children:"Verification & Google Analytics"}),(0,n.jsxs)("p",{className:"text-sm text-muted-foreground mt-1",children:["Connect Search Console and other tools via meta tags on the homepage, and optionally add a GA4 measurement ID for sitewide analytics (public pages only, not"," ",(0,n.jsx)("code",{className:"text-xs bg-muted px-1 py-0.5 rounded",children:"/admin"}),")."]})]}),l?(0,n.jsx)("div",{className:"py-10 flex justify-center",children:(0,n.jsx)("div",{className:"h-6 w-6 animate-spin rounded-full border-2 border-muted border-t-foreground"})}):(0,n.jsxs)("div",{className:"space-y-6",children:[(0,n.jsxs)("div",{id:"admin-google-analytics",className:"rounded-2xl border bg-card p-5 space-y-3 scroll-mt-24",children:[(0,n.jsxs)("div",{className:"flex items-center justify-between",children:[(0,n.jsx)("p",{className:"font-semibold text-sm",children:"Google Analytics 4"}),(0,n.jsx)("a",{href:"https://support.google.com/analytics/answer/9539598",target:"_blank",rel:"noopener noreferrer",className:"text-xs text-primary hover:underline",children:"Find your measurement ID →"})]}),(0,n.jsxs)("div",{className:"grid gap-1.5",children:[(0,n.jsx)(tH,{htmlFor:"google_analytics_measurement_id",className:"text-xs text-muted-foreground",children:"Measurement ID"}),(0,n.jsx)(tR.p,{id:"google_analytics_measurement_id",value:d.google_analytics_measurement_id,onChange:e=>{p(""),c(t=>({...t,google_analytics_measurement_id:e.target.value}))},placeholder:"G-XXXXXXXXXX",autoComplete:"off"}),(0,n.jsx)("p",{className:"text-xs text-muted-foreground",children:"Leave empty to disable. The live site injects the official gtag snippet into the first HTML (build + Netlify Edge) so Google’s tag tester sees it; the app still sends SPA page views on navigation."}),h?(0,n.jsx)("p",{className:"text-xs text-destructive font-medium",children:h}):null]})]}),sf.map(e=>(0,n.jsxs)("div",{className:"rounded-2xl border bg-card p-5 space-y-3",children:[(0,n.jsxs)("div",{className:"flex items-center justify-between",children:[(0,n.jsx)("p",{className:"font-semibold text-sm",children:e.label}),(0,n.jsxs)("a",{href:e.link,target:"_blank",rel:"noopener noreferrer",className:"text-xs text-primary hover:underline",children:["Get your co
1de from ",e.linkLabel," →"]})]}),(0,n.jsxs)("div",{className:"grid gap-1.5",children:[(0,n.jsx)(tH,{htmlFor:e.key,className:"text-xs text-muted-foreground",children:(0,n.jsx)("code",{children:'<meta name="'.concat(e.metaName,'" content="..." />')})}),(0,n.jsx)(tR.p,{id:e.key,value:d[e.key],onChange:t=>c(r=>({...r,[e.key]:t.target.value})),placeholder:e.placeholder}),(0,n.jsx)("p",{className:"text-xs text-muted-foreground",children:e.hint})]})]},e.key)),g.isError?(0,n.jsxs)("div",{className:"rounded-lg border border-destructive/30 bg-destructive/10 px-3 py-2 text-sm text-destructive",children:["Save failed: ",(null==(e=g.error)?void 0:e.message)||"Unknown error"]}):null,(0,n.jsxs)("div",{className:"flex items-center gap-3",children:[(0,n.jsx)(L.Button,{type:"button",onClick:function(){var e;let t=String(null!=(e=d.google_analytics_measurement_id)?e:"").trim(),r=function(e){let t=String(null!=e?e:"").trim().toUpperCase();return t&&/^G-[A-Z0-9]+$/.test(t)?t:""}(t);if(t&&!r)return void p("Enter a valid GA4 measurement ID (example: G-XXXXXXXXXX).");p("");let n=Object.fromEntries(sf.map(e=>{let t=function(e){let t=String(null!=e?e:"").trim();if(!t)return"";if(/<meta\s/i.test(t)){let e=t.match(/content\s*=\s*["']([^"']*)["']/i);if(e)return e[1].trim();let r=t.match(/content\s*=\s*([^\s/>]+)/i);if(r)return r[1].replace(/^["']|["']$/g,"").trim()}return t.replace(/^["']|["']$/g,"").trim()}(d[e.key]);return[e.key,t||null]}));n.google_analytics_measurement_id=r||null,g.mutate(n)},disabled:g.isPending,children:g.isPending?"Saving…":"Save verification & analytics"}),u?(0,n.jsx)("span",{className:"text-sm text-green-600 font-medium",children:"Saved successfully."}):null]})]})]})},{})}),(0,n.jsx)(s.qh,{path:"seo/redirects",element:(0,n.jsx)(function(){let e=(0,o.jE)(),{data:t=[],isLoading:r,error:s}=(0,eK.I)({queryKey:["admin","redirects"],queryFn:sj}),[i,l]=(0,a.useState)(!1),[d,c]=(0,a.useState)(sw()),[u,m]=(0,a.useState)(null),[h,p]=(0,a.useState)(""),g=(0,tO.n)({mutationFn:async e=>{if(u){let{error:t}=await T.N.from("redirects").update({...e,updated_at:new Date().toISOString()}).eq("id",u);if(t)throw t}else{let{error:t}=await T.N.from("redirects").insert(e);if(t)throw t}},onSuccess:()=>{e.invalidateQueries({queryKey:["admin","redirects"]}),e.invalidateQueries({queryKey:["public","redirects"]}),l(!1),c(sw()),m(null),p("")},onError:e=>p((null==e?void 0:e.message)||"Save failed.")}),x=(0,tO.n)({mutationFn:async e=>{let{error:t}=await T.N.from("redirects").delete().eq("id",e);if(t)throw t},onSuccess:()=>{e.invalidateQueries({queryKey:["admin","redirects"]}),e.invalidateQueries({queryKey:["public","redirects"]})}});return(0,n.jsxs)("div",{className:"space-y-6",children:[(0,n.jsxs)("div",{className:"flex items-start justify-between gap-4",children:[(0,n.jsxs)("div",{children:[(0,n.jsx)("h1",{className:"text-2xl font-semibold",children:"Redirects"}),(0,n.jsx)("p",{className:"text-sm text-muted-foreground mt-1",children:'Manage 301/302 redirects. Changes apply instantly for in-app navigation. Use "Export _redirects" for server-side enforcement.'})]}),(0,n.jsxs)("div",{className:"flex gap-2 shrink-0",children:[t.length>0&&(0,n.jsxs)(L.Button,{type:"button",variant:"outline",onClick:()=>(function(e){let t=new Blob([e.map(e=>"".concat(e.from_path,"  ").concat(e.to_path,"  ").concat(e.redirect_type)).join("\n")+"\n"],{type:"text/plain"}),r=URL.createObjectURL(t),n=document.createElement("a");n.href=r,n.download="_redirects",n.click(),URL.revokeObjectURL(r)})(t),children:[(0,n.jsx)(rG.A,{className:"h-4 w-4 mr-1.5"}),"Export _redirects"]}),(0,n.jsx)(L.Button,{type:"button",onClick:function(){c(sw()),m(null),p(""),l(!0)},children:"Add redirect"})]})]}),s?(0,n.jsx)("div",{className:"rounded-lg border border-destructive/30 bg-destructive/10 px-3 py-2 text-sm text-destructive",children:s.message}):null,(0,n.jsxs)("div",{className:"rounded-2xl border bg-card overflow-hidden",children:[(0,n.jsxs)("div",{className:"grid grid-cols-[1fr_1fr_80px_80px] border-b px-4 py-3 text-xs font-medium text-muted-foreground",children:[(0,n.jsx)("div",{children:"From"}),(0,n.jsx)("div",{children:"To"}),(0,n.jsx)("div",{children:"Type"}),(0,n.jsx)("div",{className:"text-right",children:"Actions"})]}),r?(0,n.jsx)("div",{className:"px-4 py-6 text-sm text-muted-foreground",children:"Loading…"}):0===t.length?(0,n.jsx)("div",{className:"px-4 py-8 text-center text-sm text-muted-foreground",children:'No redirects yet. Click "Add redirect" to create one.'}):(0,n.jsx)("div",{className:"divide-y",children:t.map(e=>(0,n.jsxs)("div",{className:"grid grid-cols-[1fr_1fr_80px_80px] items-center px-4 py-3 gap-2",children:[(0,n.jsx)("div",{className:"text-sm font-mono truncate",children:e.from_path}),(0,n.jsx)("div",{className:"text-sm text-muted-foreground truncate",children:e.to_path}),(0,n.jsx)("div",{className:"text-xs",children:(0,n.jsx)("span",{className:"inline-flex items-center rounded px-1.5 py-0.5 font-medium ".concat(301===e.redirect_type?"bg-blue-50 text-blue-700":"bg-amber-50 text-amber-700"),children:e.redirect_type})}),(0,n.jsxs)("div",{className:"flex justify-end gap-1",children:[(0,n.jsx)(L.Button,{type:"button",size:"icon",variant:"ghost",className:"h-7 w-7",onClick:()=>{c({from_path:e.from_path||"",to_path:e.to_path||"",redirect_type:String(e.redirect_type||"301")}),m(e.id),p(""),l(!0)},children:(0,n.jsx)(rO.A,{className:"h-3.5 w-3.5"})}),(0,n.jsx)(L.Button,{type:"button",size:"icon",variant:"ghost",className:"h-7 w-7 text-destructive hover:text-destructive",disabled:x.isPending,onClick:()=>{confirm("Delete redirect ".concat(e.from_path,"?"))&&x.mutate(e.id)},children:(0,n.jsx)(rW.A,{className:"h-3.5 w-3.5"})})]})]},e.id))})]}),(0,n.jsxs)(tQ,{open:i,onOpenChange:e=>{l(e),e||(c(sw()),m(null),p(""))},children:[(0,n.jsx)(tY,{asChild:!0,children:(0,n.jsx)("span",{})}),(0,n.jsxs)(tX,{className:"max-w-lg",children:[(0,n.jsx)(tZ,{children:(0,n.jsx)(t1,{children:u?"Edit redirect":"Add redirect"})}),(0,n.jsxs)("div",{className:"space-y-4 pt-2",children:[(0,n.jsxs)("div",{className:"grid gap-1.5",children:[(0,n.jsx)(tH,{htmlFor:"from_path",children:"From path"}),(0,n.jsx)(tR.p,{id:"from_path",value:d.from_path,onChange:e=>c(t=>({...t,from_path:e.target.value})),placeholder:"/old-page"}),(0,n.jsx)("p",{className:"text-xs text-muted-foreground",children:"The old URL path visitors will arrive at."})]}),(0,n.jsxs)("div",{className:"grid gap-1.5",children:[(0,n.jsx)(tH,{htmlFor:"to_path",children:"To URL / path"}),(0,n.jsx)(tR.p,{id:"to_path",value:d.to_path,onChange:e=>c(t=>({...t,to_path:e.target.value})),placeholder:"/new-page or https://example.com"}),(0,n.jsx)("p",{className:"text-xs text-muted-foreground",children:"Destination path or full URL."})]}),(0,n.jsxs)("div",{className:"grid gap-1.5",children:[(0,n.jsx)(tH,{htmlFor:"redirect_type",children:"Redirect type"}),(0,n.jsxs)(rl,{value:d.redirect_type,onValueChange:e=>c(t=>({...t,redirect_type:e})),children:[(0,n.jsx)(rd,{id:"redirect_type",children:(0,n.jsx)(ro,{})}),(0,n.jsxs)(rm,{children:[(0,n.jsx)(rh,{value:"301",children:"301 — Moved Permanently"}),(0,n.jsx)(rh,{value:"302",children:"302 — Found (Temporary)"})]})]})]}),h?(0,n.jsx)("div",{className:"rounded-lg border border-destructive/30 bg-destructive/10 px-3 py-2 text-sm text-destructive",children:h}):null,(0,n.jsxs)("div",{className:"flex justify-end gap-2 pt-1",children:[(0,n.jsx)(L.Button,{type:"button",variant:"outline",onClick:()=>l(!1),children:"Cancel"}),(0,n.jsx)(L.Button,{type:"button",onClick:function(){p("");let e=function(e){let t=String(e||"").trim();return t?t.startsWith("/")?t:"/".concat(t):""}(d.from_path),t=d.to_path.trim();return e?t?void g.mutate({from_path:e,to_path:t,redirect_type:Number(d.redirect_type)}):void p("To URL / path is required."):void p("From path is required.")},disabled:g.isPending,children:g.isPending?"Saving…":"Save"})]})]})]})]})]})},{})}),(0,n.jsx)(s.qh,{path:"auto-linking",element:(0,n.jsx)(function(){let e=(0,o.jE)(),{data:t,isLoading:r,error:s,isSuccess:l}=(0,eK.I)({queryKey:n$,queryFn:nZ,staleTime:6e4}),d=(0,a.useRef)(""),[c,u]=(0,a.useState)(!1),[m,h]=(0,a.useState)(0),p=(0,a.useCallback)(()=>h(e=>e+1),[]),[g,x]=(0,a.useState)(()=>nJ().internalLinkSitemapPaste);(0,a.useEffect)(()=>
1{if(!l)return;n1(null!=t?t:null);let e=nJ().internalLinkSitemapPaste;x(e),d.current=e,u(!0),p()},[t,l,p]);let v=(0,tO.n)({mutationFn:async()=>n0({internal_link_sitemap_paste:g}),onSuccess:async t=>{n1(t),await e.invalidateQueries({queryKey:["admin","site_settings"]}),await e.invalidateQueries({queryKey:n$});let r=nJ().internalLinkSitemapPaste;x(r),d.current=r,p(),f({title:"Auto Linking saved",description:"Sitemap is stored in the database for all admins."})},onError:e=>{f({title:"Could not save",description:(null==e?void 0:e.message)||"Run scripts/ensure-site-settings-admin-workspace.sql if the column is missing.",variant:"destructive"})}}),y=(0,a.useMemo)(()=>!!c&&g!==d.current,[g,m,c]),b=(0,a.useCallback)(()=>{x(d.current)},[]);ep({isDirty:y,variant:"settings",onSave:(0,a.useCallback)(async()=>{await v.mutateAsync()},[v]),onDiscard:b});let j=(0,a.useMemo)(()=>e3(g),[g]);return(0,n.jsxs)("div",{className:"space-y-6 max-w-3xl",children:[(0,n.jsxs)("div",{className:"flex flex-col gap-4 sm:flex-row sm:items-start sm:justify-between",children:[(0,n.jsxs)("div",{className:"flex gap-3",children:[(0,n.jsx)("div",{className:"rounded-xl border bg-muted/40 p-2.5",children:(0,n.jsx)(s_.A,{className:"h-6 w-6 text-muted-foreground"})}),(0,n.jsxs)("div",{children:[(0,n.jsx)("h1",{className:"text-2xl font-semibold",children:"Auto Linking"}),(0,n.jsxs)("p",{className:"text-sm text-muted-foreground mt-1 max-w-2xl",children:["Configure what the AI is allowed to link to. On the blog editor, ",(0,n.jsx)("strong",{className:"text-foreground font-medium",children:"Analyze"})," ","uses this allowlist for internal URLs. One admin can paste the sitemap here; everyone else picks it up automatically. Until the DB column exists, this page falls back to legacy"," ",(0,n.jsx)("code",{className:"text-xs",children:"localStorage"})," for this browser."]})]})]}),(0,n.jsx)(L.Button,{type:"button",onClick:function(){v.mutateAsync()},disabled:v.isPending||!c,children:v.isPending?"Saving…":"Save"})]}),s?(0,n.jsx)("div",{className:"rounded-lg border border-destructive/30 bg-destructive/10 px-3 py-2 text-sm text-destructive",children:s.message}):null,s||!r&&c?null:(0,n.jsx)("div",{className:"text-sm text-muted-foreground",children:"Loading workspace settings…"}),(0,n.jsxs)("div",{className:"rounded-2xl border bg-card p-5 space-y-3",children:[(0,n.jsxs)("div",{children:[(0,n.jsx)("p",{className:"text-sm font-medium",children:"Internal links — sitemap paste"}),(0,n.jsxs)("p",{className:"text-xs text-muted-foreground mt-1 leading-relaxed",children:["Paste your ",(0,n.jsx)("code",{className:"text-xs",children:"sitemap.xml"})," (with ",(0,n.jsx)("code",{className:"text-xs",children:"<loc>"})," tags) or one URL/path per line (e.g. ",(0,n.jsx)("code",{className:"text-xs",children:"https://yoursite.com/about"})," or ",(0,n.jsx)("code",{className:"text-xs",children:"/programs/private-label"}),"). AI may only suggest destinations from this list."]})]}),(0,n.jsxs)("div",{className:"grid gap-2",children:[(0,n.jsx)(tH,{htmlFor:"auto-link-sitemap",children:"Sitemap / URLs"}),(0,n.jsx)(rP.T,{id:"auto-link-sitemap",value:g,onChange:e=>x(e.target.value),placeholder:'<?xml version="1.0"?> ... <loc>https://...</loc> ...\n\nor\n\n/blog/my-post\n/catalog/mens-wear',rows:14,className:"font-mono text-xs min-h-[200px]"})]}),(0,n.jsxs)("p",{className:"text-xs text-muted-foreground",children:["Parsed ",(0,n.jsx)("span",{className:"text-foreground font-medium",children:j.length})," unique internal paths with usable hints. Empty means nothing to link until you paste a sitemap."]}),(0,n.jsxs)("p",{className:"text-xs text-muted-foreground",children:["Model and API keys: ",(0,n.jsx)(i.N_,{to:"/admin/api-settings/",className:"text-primary hover:underline",children:"API Settings"}),"."]})]})]})},{})}),(0,n.jsx)(s.qh,{path:"api-settings",element:(0,n.jsx)(function(){let e=(0,o.jE)(),{data:t,isLoading:r,error:s,isSuccess:l}=(0,eK.I)({queryKey:n$,queryFn:nZ,staleTime:6e4}),d=(0,a.useRef)(""),[c,u]=(0,a.useState)(!1),[m,h]=(0,a.useState)(0),p=(0,a.useCallback)(()=>h(e=>e+1),[]),[g,x]=(0,a.useState)(()=>nl());(0,a.useEffect)(()=>
1{if(!l)return;n1(null!=t?t:null);let e=nl();x(e),d.current=JSON.stringify(e),u(!0),p()},[t,l,p]);let v=(0,tO.n)({mutationFn:async()=>{var e;if(!sA.includes(g.internalLinksProvider)){let e=Error("INVALID_PROVIDER");throw e.code="INVALID_PROVIDER",e}let t=Object.fromEntries(sA.map(e=>[e,(g.keys[e]||[]).map(e=>String(e).trim()).filter(Boolean)])),r=await sC(t,{timeoutMs:14e3});if(!r.ok){let e=Error("API_KEY_VALIDATION");throw e.code="API_KEY_VALIDATION",e.failures=r.failures,e}return n0({admin_ai_settings:{v:null!=(e=g.v)?e:1,internalLinksProvider:g.internalLinksProvider,models:{...g.models},keys:t}})},onSuccess:async t=>{n1(t),await e.invalidateQueries({queryKey:["admin","site_settings"]}),await e.invalidateQueries({queryKey:n$});let r=nl();x(r),d.current=JSON.stringify(r),p(),f({title:"API settings saved",description:"Stored in the database for all admins. Keys are sensitive — restrict usage in each provider console."})},onError:e=>{if((null==e?void 0:e.code)==="INVALID_PROVIDER"||(null==e?void 0:e.message)==="INVALID_PROVIDER")return void f({title:"Invalid provider",description:"Choose a valid AI provider."});if((null==e?void 0:e.code)==="API_KEY_VALIDATION"&&Array.isArray(e.failures)){let t=e.failures.map(e=>e.message).join(" ");f({title:"API key check failed",description:t.length>480?"".concat(t.slice(0,480),"…"):t,variant:"destructive"});return}f({title:"Could not save",description:(null==e?void 0:e.message)||"Check your connection and that site_settings row id=1 exists.",variant:"destructive"})}}),y=(0,a.useMemo)(()=>!!c&&JSON.stringify(g)!==d.current,[g,m,c]),b=(0,a.useCallback)(()=>{try{x(JSON.parse(d.current))}catch(e){x(nl())}},[]);function j(e){let t=g.keys[e];return Array.isArray(t)&&t.length?t:[""]}function w(e,t){x(r=>({...r,models:{...r.models,[e]:t}}))}return ep({isDirty:y,variant:"settings",onSave:(0,a.useCallback)(async()=>{await v.mutateAsync()},[v]),onDiscard:b}),(0,n.jsxs)("div",{className:"space-y-6 w-full min-w-0 max-w-none",children:[(0,n.jsxs)("div",{className:"flex flex-col gap-4 sm:flex-row sm:items-start sm:justify-between",children:[(0,n.jsxs)("div",{className:"flex gap-3",children:[(0,n.jsx)("div",{className:"rounded-xl border bg-muted/40 p-2.5",children:(0,n.jsx)(sN.A,{className:"h-6 w-6 text-muted-foreground"})}),(0,n.jsxs)("div",{children:[(0,n.jsx)("h1",{className:"text-2xl font-semibold",children:"API Settings"}),(0,n.jsx)("p",{className:"text-sm text-muted-foreground mt-1",children:"Blog AI linking uses these provider keys and models; one save applies for every admin. Save verifies each non-empty key with the provider before storing."})]})]}),(0,n.jsx)(L.Button,{type:"button",onClick:function(){v.mutateAsync()},disabled:v.isPending||!c,children:v.isPending?"Verifying / saving…":"Save"})]}),s?(0,n.jsx)("div",{className:"rounded-lg border border-destructive/30 bg-destructive/10 px-3 py-2 text-sm text-destructive w-full",children:s.message}):null,s||!r&&c?null:(0,n.jsx)("div",{className:"text-sm text-muted-foreground",children:"Loading workspace settings…"}),(0,n.jsxs)("div",{className:"rounded-2xl border bg-card p-5 space-y-4 w-full",children:[(0,n.jsx)("p",{className:"text-sm font-medium",children:"Internal & external links — default AI"}),(0,n.jsxs)("p",{className:"text-xs text-muted-foreground",children:["The blog editor uses this provider and model for ",(0,n.jsx)("span",{className:"text-foreground",children:"Add (AI)"}),"."," ",(0,n.jsx)(i.N_,{to:"/admin/blog/new/",className:"text-primary hover:underline",children:"Open blog editor"})]}),(0,n.jsxs)("div",{className:"grid sm:grid-cols-2 gap-4",children:[(0,n.jsxs)("div",{className:"grid gap-2",children:[(0,n.jsx)(tH,{children:"Provider"}),(0,n.jsxs)(rl,{value:g.internalLinksProvider,onValueChange:e=>{x(t=>({...t,internalLinksProvider:e}))},children:[(0,n.jsx)(rd,{children:(0,n.jsx)(ro,{placeholder:"Provider"})}),(0,n.jsx)(rm,{position:"popper",className:"max-h-72",children:r3.map(e=>(0,n.jsx)(rh,{value:e.id,children:e.name},e.id))})]})]}),(0,n.jsxs)("div",{className:"grid gap-2",children:[(0,n.jsx)(tH,{children:"Model for this provider"}),(0,n.jsxs)(rl,{value:sE(g.internalLinksProvider,g.models),onValueChange:e=>w(g.internalLinksProvider,e),children:[(0,n.jsx)(rd,{children:(0,n.jsx)(ro,{placeholder:"Choose model"})}),(0,n.jsx)(rm,{position:"popper",className:"max-h-72",children:(r5[g.internalLinksProvider]||[]).map(e=>(0,n.jsx)(rh,{value:e.value,children:e.label},e.value))})]})]})]})]}),(0,n.jsxs)("div",{className:"space-y-4 w-full min-w-0",children:[(0,n.jsx)("h2",{className:"text-lg font-medium",children:"Provider API keys"}),(0,n.jsxs)("p",{className:"text-sm text-muted-foreground w-full max-w-none",children:["Add multiple keys per provider to rotate fairly; if one hits a limit or fails, the next key is tried automatically. The internal-link provider needs at least one key (or"," ",(0,n.jsx)("code",{className:"text-xs",children:"VITE_GEMINI_API_KEY"})," for Gemini at build time)."]}),(0,n.jsx)("div",{className:"grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-4 w-full",children:r3.map(e=>(0,n.jsxs)("div",{className:"rounded-2xl border bg-card p-5 space-y-2 min-w-0",children:[(0,n.jsx)(tH,{className:"text-base font-medium",children:e.name}),(0,n.jsx)("p",{className:"text-xs text-muted-foreground",children:e.keyLabel}),(0,n.jsxs)("div",{className:"space-y-2",children:[j(e.id).map((t,r)=>(0,n.jsxs)("div",{className:"flex gap-2 items-center min-w-0",children:[(0,n.jsx)(tR.p,{id:0===r?"key-".concat(e.id):void 0,type:"password",autoComplete:"off",placeholder:0===r?e.keyPlaceholder:"Another ".concat(e.name," key"),className:"min-w-0 flex-1",value:t,onChange:t=>{var n,a;return n=e.id,a=t.target.value,void x(e=>{let t=e.keys[n],s=Array.isArray(t)&&t.length?[...t]:[""];return s[r]=a,{...e,keys:{...e.keys,[n]:s}}})}}),j(e.id).length>1?(0,n.jsx)(L.Button,{type:"button",variant:"outline",size:"icon",className:"shrink-0",onClick:()=>{var t;return t=e.id,void x(e=>{let n=e.keys[t],a=Array.isArray(n)?[...n]:[""];return a.splice(r,1),{...e,keys:{...e.keys,[t]:a.length?a:[""]}}})},"aria-label":"Remove key ".concat(r+1),children:(0,n.jsx)(rW.A,{className:"h-4 w-4"})}):null]},"".concat(e.id,"-k-").concat(r))),(0,n.jsxs)(L.Button,{type:"button",variant:"outline",size:"sm",className:"w-full gap-2",onClick:()=>{var t;return t=e.id,void x(e=>{let r=e.keys[t],n=Array.isArray(r)?[...r]:[""];return n.push(""),{...e,keys:{...e.keys,[t]:n}}})},children:[(0,n.jsx)(af.A,{className:"h-4 w-4"}),"Add another key"]})]}),(0,n.jsxs)("div",{className:"grid gap-2 pt-2",children:[(0,n.jsxs)(tH,{className:"text-xs font-normal text-muted-foreground",children:["Saved model preset for ",e.name]}),(0,n.jsxs)(rl,{value:sE(e.id,g.models),onValueChange:t=>w(e.id,t),children:[(0,n.jsx)(rd,{className:"w-full",children:(0,n.jsx)(ro,{placeholder:"Model"})}),(0,n.jsx)(rm,{position:"popper",className:"max-h-72",children:(r5[e.id]||[]).map(e=>(0,n.jsx)(rh,{value:e.value,children:e.label},e.value))})]})]})]},e.id))})]})]})},{})}),(0,n.jsxs)(s.qh,{path:"settings",children:[(0,n.jsx)(s.qh,{index:!0,element:(0,n.jsx)(s.C5,{to:"general",replace:!0})}),(0,n.jsx)(s.qh,{path:"general",element:(0,n.jsx)(function(){let e=(0,o.jE)(),{data:t,isLoading:r,error:s}=(0,eK.I)({queryKey:["admin","site_settings"],queryFn:sP}),l=(0,a.useRef)(""),d=(0,a.useRef)(!1),[c,u]=(0,a.useState)(0),m=(0,a.useCallback)(()=>u(e=>e+1),[]),[h,p]=(0,a.useState)(()=>sR({}));(0,a.useEffect)(()=>
1{if(!t)return;let e=sR(t);p(e),l.current=JSON.stringify(e),d.current=!0,m()},[t,m]);let g=(0,a.useMemo)(()=>{try{var e,t;let r=(e=h.date_format,t=h.date_format_custom,"custom"===e&&(null==t?void 0:t.trim())?t.trim():({"F j, Y":"MMMM d, yyyy","Y-m-d":"yyyy-MM-dd","m/d/Y":"MM/dd/yyyy","d/m/Y":"dd/MM/yyyy"})[e]||"MMMM d, yyyy");return(0,to.GP)(new Date,r)}catch(e){return"—"}},[h.date_format,h.date_format_custom]),x=(0,a.useMemo)(()=>{try{var e,t;let r=(e=h.time_format,t=h.time_format_custom,"custom"===e&&(null==t?void 0:t.trim())?t.trim():({"g:i a":"h:mm a","g:i A":"h:mm a","H:i":"HH:mm"})[e]||"h:mm a");return(0,to.GP)(new Date,r)}catch(e){return"—"}},[h.time_format,h.time_format_custom]),f=(0,tO.n)({mutationFn:async()=>{let e=sM(t),r={...e,general:{...e.general,tagline:h.tagline||"",site_icon_url:h.site_icon_url||"",admin_email:h.admin_email||"",anyone_can_register:!!h.anyone_can_register,default_role:h.default_role||"subscriber",timezone:h.timezone||"UTC",date_format:h.date_format,date_format_custom:h.date_format_custom||"",time_format:h.time_format,time_format_custom:h.time_format_custom||"",week_starts_on:Number(h.week_starts_on)||0}},n={id:1,site_name:h.site_name||null,site_url:h.site_url||null,default_seo_title:h.default_seo_title||null,default_seo_description:h.default_seo_description||null,default_keywords:h.default_keywords||null,default_og_image:h.default_og_image||null,default_twitter_image:h.default_twitter_image||null,robots_index:!!h.robots_index,robots_follow:!!h.robots_follow,cms_options:r,updated_at:new Date().toISOString()},{data:a,error:s}=await T.N.from("site_settings").upsert(n).select("*").single();if(s)throw s;return a},onSuccess:async t=>{await e.invalidateQueries({queryKey:["admin","site_settings"]});let r=sR(t);p(r),l.current=JSON.stringify(r),m()}}),v=(0,a.useMemo)(()=>!!d.current&&JSON.stringify(h)!==l.current,[h,c]),y=(0,a.useCallback)(()=>{try{p(JSON.parse(l.current))}catch(e){}},[]);ep({isDirty:v,variant:"settings",onSave:(0,a.useCallback)(async()=>{await f.mutateAsync()},[f]),onDiscard:y});let b=(e,t)=>p(r=>({...r,[e]:t})),j=(e,t,r)=>(0,n.jsxs)("div",{className:"grid gap-2 sm:grid-cols-[minmax(160px,220px)_1fr] sm:items-start sm:gap-6 border-b border-border/60 py-4 last:border-0",children:[(0,n.jsxs)("div",{className:"pt-1.5",children:[(0,n.jsx)(tH,{className:"text-foreground font-medium",children:e}),t?(0,n.jsx)("p",{className:"text-xs text-muted-foreground mt-1",children:t}):null]}),(0,n.jsx)("div",{className:"min-w-0",children:r})]});return(0,n.jsxs)("div",{className:"w-full min-w-0 max-w-full space-y-6 pb-8",children:[(0,n.jsxs)("div",{className:"flex flex-wrap items-start justify-between gap-4",children:[(0,n.jsxs)("div",{children:[(0,n.jsxs)("p",{className:"text-sm text-muted-foreground mb-1",children:[(0,n.jsx)(i.N_,{to:"/admin/settings/general/",className:"hover:underline",children:"Settings"})," ","/ General"]}),(0,n.jsx)("h1",{className:"text-2xl font-semibold",children:"General Settings"}),(0,n.jsx)("p",{className:"text-sm text-muted-foreground mt-1",children:"Site identity, regional formats, and default SEO."})]}),(0,n.jsx)(L.Button,{type:"button",onClick:()=>f.mutate(),disabled:f.isPending,children:f.isPending?"Saving…":"Save changes"})]}),s?(0,n.jsx)("div",{className:"rounded-lg border border-destructive/30 bg-destructive/10 px-3 py-2 text-sm text-destructive",children:s.message}):null,r?(0,n.jsx)("div",{className:"text-sm text-muted-foreground",children:"Loading…"}):null,(0,n.jsxs)("div",{className:"rounded-2xl border bg-card p-6 shadow-sm space-y-0 divide-y divide-border/60",children:[(0,n.jsx)("div",{className:"pb-2 font-medium text-sm text-muted-foreground uppercase tracking-wide",children:"Site"}),j("Site title","Shown in titles and admin.",(0,n.jsx)(tR.p,{value:h.site_name,onChange:e=>b("site_name",e.target.value)})),j("Tagline","In a few words, explain what this site is about.",(0,n.jsx)(tR.p,{value:h.tagline,onChange:e=>b("tagline",e.target.value),placeholder:"Just another apparel manufacturer"})),j("Site icon","Square image, at least 512\xd7512 — used for favicon / PWA.",(0,n.jsxs)("div",{className:"space-y-2",children:[(0,n.jsx)(rF,{label:"Upload",value:h.site_icon_url,onChange:e=>b("site_icon_url",e)}),(0,n.jsx)(tR.p,{className:"font-mono text-sm",value:h.site_icon_url,onChange:e=>b("site_icon_url",e.target.value),placeholder:"https://…"})]})),j("Site address (URL)","Canonical site URL for links. Build also uses VITE_SITE_URL (".concat(eS.W6,") when set."),(0,n.jsx)(tR.p,{value:h.site_url,onChange:e=>b("site_url",e.target.value),placeholder:"https://apparglobal.com"})),j("Administration email","Used for future notifications (not wired to SMTP yet).",(0,n.jsx)(tR.p,{type:"email",value:h.admin_email,onChange:e=>b("admin_email",e.target.value),placeholder:"[email protected]"})),j("Membership",null,(0,n.jsxs)("label",{className:"flex items-center gap-2 text-sm",children:[(0,n.jsx)("input",{type:"checkbox",className:"h-4 w-4 roun
1ded border-input",checked:h.anyone_can_register,onChange:e=>b("anyone_can_register",e.target.checked)}),"Anyone can register (reserved — public registration not enforced by this app yet)"]})),j("New user default role",null,(0,n.jsxs)(rl,{value:h.default_role,onValueChange:e=>b("default_role",e),children:[(0,n.jsx)(rd,{className:"w-full max-w-full sm:max-w-md",children:(0,n.jsx)(ro,{})}),(0,n.jsxs)(rm,{children:[(0,n.jsx)(rh,{value:"subscriber",children:"Subscriber"}),(0,n.jsx)(rh,{value:"contributor",children:"Contributor"}),(0,n.jsx)(rh,{value:"author",children:"Author"}),(0,n.jsx)(rh,{value:"editor",children:"Editor"})]})]})),(0,n.jsx)("div",{className:"pt-6 pb-2 font-medium text-sm text-muted-foreground uppercase tracking-wide",children:"Locale"}),j("Timezone",null,(0,n.jsxs)(rl,{value:h.timezone,onValueChange:e=>b("timezone",e),children:[(0,n.jsx)(rd,{className:"w-full max-w-full sm:max-w-xl",children:(0,n.jsx)(ro,{})}),(0,n.jsx)(rm,{children:sO.map(e=>(0,n.jsx)(rh,{value:e,children:e},e))})]})),j("Date format","Preview: ".concat(g),(0,n.jsxs)("div",{className:"space-y-3",children:[(0,n.jsx)("div",{className:"flex flex-col gap-2",children:sI.map(e=>(0,n.jsxs)("label",{className:"flex items-center gap-2 text-sm",children:[(0,n.jsx)("input",{type:"radio",name:"datefmt",checked:h.date_format===e.value,onChange:()=>b("date_format",e.value)}),e.label]},e.value))}),"custom"===h.date_format?(0,n.jsx)(tR.p,{className:"font-mono text-sm w-full max-w-full sm:max-w-xl",placeholder:"date-fns pattern",value:h.date_format_custom,onChange:e=>b("date_format_custom",e.target.value)}):null]})),j("Time format","Preview: ".concat(x),(0,n.jsxs)("div",{className:"space-y-3",children:[(0,n.jsx)("div",{className:"flex flex-col gap-2",children:sL.map(e=>(0,n.jsxs)("label",{className:"flex items-center gap-2 text-sm",children:[(0,n.jsx)("input",{type:"radio",name:"timefmt",checked:h.time_format===e.value,onChange:()=>b("time_format",e.value)}),e.label]},e.value))}),"custom"===h.time_format?(0,n.jsx)(tR.p,{className:"font-mono text-sm w-full max-w-full sm:max-w-xl",placeholder:"date-fns pattern",value:h.time_format_custom,onChange:e=>b("time_format_custom",e.target.value)}):null]})),j("Week starts on",null,(0,n.jsxs)(rl,{value:String(h.week_starts_on),onValueChange:e=>b("week_starts_on",Number(e)),children:[(0,n.jsx)(rd,{className:"w-full max-w-full sm:max-w-md",children:(0,n.jsx)(ro,{})}),(0,n.jsxs)(rm,{children:[(0,n.jsx)(rh,{value:"0",children:"Sunday"}),(0,n.jsx)(rh,{value:"1",children:"Monday"}),(0,n.jsx)(rh,{value:"2",children:"Tuesday"}),(0,n.jsx)(rh,{value:"3",children:"Wednesday"}),(0,n.jsx)(rh,{value:"4",children:"Thursday"}),(0,n.jsx)(rh,{value:"5",children:"Friday"}),(0,n.jsx)(rh,{value:"6",children:"Saturday"})]})]})),(0,n.jsx)("div",{className:"pt-6 pb-2 font-medium text-sm text-muted-foreground uppercase tracking-wide",children:"Search engine visibility and defaults"}),j("Default SEO title",null,(0,n.jsx)(tR.p,{value:h.default_seo_title,onChange:e=>b("default_seo_title",e.target.value)})),j("Default meta description",null,(0,n.jsx)(rP.T,{value:h.default_seo_description,onChange:e=>b("default_seo_description",e.target.value),rows:4})),j("Default keywords",null,(0,n.jsx)(rP.T,{value:h.default_keywords,onChange:e=>b("default_keywords",e.target.value),rows:3})),j("Indexing (default)","When a page has no SEO override, allow indexing.",(0,n.jsxs)("label",{className:"flex items-center gap-2 text-sm",children:[(0,n.jsx)("input",{type:"checkbox",className:"h-4 w-4",checked:!!h.robots_index,onChange:e=>b("robots_index",e.target.checked)}),"Allow search engines to index by default"]})),j("Follow (default)",null,(0,n.jsxs)("label",{className:"flex items-center gap-2 text-sm",children:[(0,n.jsx)("input",{type:"checkbox",className:"h-4 w-4",checked:!!h.robots_follow,onChange:e=>b("robots_follow",e.target.checked)}),"Allow following links by default"]}))]}),(0,n.jsxs)("div",{className:"grid lg:grid-cols-2 gap-6 w-full min-w-0",children:[(0,n.jsx)("div",{className:"rounded-2xl border bg-card p-5",children:(0,n.jsx)(rF,{label:"Default OG image",value:h.default_og_image,onChange:e=>b("default_og_image",e)})}),(0,n.jsx)("div",{className:"rounded-2xl border bg-card p-5",children:(0,n.jsx)(rF,{label:"Default Twitter image (optional)",value:h.default_twitter_image,onChange:e=>b("default_twitter_image",e)})})]}),(0,n.jsx)(L.Button,{type:"button",onClick:()=>f.mutate(),disabled:f.isPending,children:f.isPending?"Saving…":"Save changes"})]})},{})})]})]}),(0,n.jsx)(s.qh,{path:"*",element:(0,n.jsx)(function(e){let{}=e,t=(0,tu.zy)(),r=t.pathname.substring(1),a=(0,tm.VI)(t.pathname,"Page not found (404) | ".concat(eS.yy),"The page you requested could not be found on Appar Global.");return(0,n.jsxs)("div",{className:"min-h-screen flex items-center justify-center p-6 bg-slate-50",children:[(0,n.jsxs)(ew.mg,{children:[(0,n.jsxs)("title",{children:["Page not found (404) | ",eS.yy]}),(0,n.jsx)("meta",{name:"description",content:"The page you requested could not be found on Appar Global."}),(0,n.jsx)("meta",{name:"keywords",content:a}),(0,n.jsx)("meta",{name:"robots",content:"noindex, nofollow"})]}),(0,n.jsx)("div",{className:"max-w-md w-full",children:(0,n.jsxs)("div",{className:"text-center space-y-6",children:[(0,n.jsxs)("div",{className:"space-y-2",children:[(0,n.jsx)("h1",{className:"text-7xl font-light text-slate-300",children:"404"}),(0,n.jsx)("div",{className:"h-0.5 w-16 bg-slate-200 mx-auto"})]}),(0,n.jsxs)("div",{className:"space-y-3",children:[(0,n.jsx)("h2",{className:"text-2xl font-medium text-slate-800",children:"Page Not Found"}),(0,n.jsxs)("p",{className:"text-slate-600 leading-relaxed",children:["The page ",(0,n.jsxs)("span",{className:"font-medium text-slate-700",children:['"',r,'"']})," could not be found in this application."]})]}),(0,n.jsx)("div",{className:"pt-6",children:(0,n.jsxs)("button",{onClick:()=>window.location.href="/",className:"inline-flex items-center px-4 py-2 text-sm font-medium text-slate-700 bg-white border border-slate-200 rounded-lg hover:bg-slate-50 hover:border-slate-300 transition-colors duration-200 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-slate-500",children:[(0,n.jsx)("svg",{className:"w-4 h-4 mr-2",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:(0,n.jsx)("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M3 12l2-2m0 0l7-7 7 7M5 10v10a1 1 0 001 1h3m10-11l2 2m-2-2v10a1 1 0 01-1 1h-3m-6 0a1 1 0 001-1v-4a1 1 0 011-1h2a1 1 0 011 1v4a1 1 0 001 1m-6 0h6"})}),"Go Home"]})})]})})]})},{})})]}));function sB(){let[e]=(0,a.useState)(()=>new l.E({defaultOptions:{queries:{retry:1}}})),[t]=(0,a.useState)(()=>(0,i.Ys)(sD));return(0,n.jsx)(o.Ht,{client:e,children:(0,n.jsxs)(P,{children:[(0,n.jsx)(i.pg,{router:t}),(0,n.jsx)(A,{}),(0,n.jsx)(E.l$,{})]})})}}}]);

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.