1import{r as c,j as e,k as hs,m as xs}from"./react-vendor-DTEXiHme.js";import{c as vt,u as je,s as U,b as Ge,N as se,X as kt,B as N,ab as L,a as Se,d as he,i as Tt,l as Jt,T as xt,ag as gs,v as Yt,ah as fs,ai as _s,aj as ys,$ as vs,x as Ze,y as me,Z as Be,_ as Ue,z as Te,C as Nt,S as gt,J as bs,a1 as at,K as js,g as Ns,a0 as ws,Q as ks,P as qt}from"./index-Cas2BA8G.js";import{T as Cs,a as Ss,b as Qe,c as He}from"./tabs-C_TdZTlp.js";import{S as re,a as ie,b as ne,c as le,d as J}from"./select-Dd8j6Fts.js";import{G as St}from"./GuidedTooltip-ErlMkTja.js";import{a as Zt,u as Xt}from"./useLists-BhKy-gxZ.js";import{I as te}from"./input-COMpcq49.js";import{L as W}from"./label-CPIAGVc8.js";import{S as Ee,a as Pe,b as ze,c as Me,e as qe,d as rt}from"./sheet-DgWE-ybh.js";import{A as it,a as nt,b as lt,c as ot,d as ct,e as dt,f as ut,g as pt}from"./alert-dialog-Cc121-Mn.js";import{u as Xe,a as As}from"./usePimSchema-Dk038bAw.js";import{S as Ce}from"./switch-CuPZPfg3.js";import{T as Lt}from"./textarea-Db7f5MqQ.js";import{P as Ne}from"./plus-BnJ7jTMP.js";import{G as wt}from"./grip-vertical-mu8zL--M.js";import{A as At}from"./arrow-up-CIk-09Z9.js";import{A as es}from"./arrow-down-XUl8eEu7.js";import{P as We}from"./pencil-DRRIH9sd.js";import{T as $e}from"./trash-2-Cha7UE-i.js";import{a as ts,V as Ds}from"./useRepositories-BmyXOq4-.js";import{w as ss,x as Rs,y as Fs,z as Ts}from"./radix-C8G44Doi.js";import{B as as}from"./bot-Dd7VnIS-.js";import{Z as rs}from"./zap-BBKoBAno.js";import{E as Ls}from"./eye-PJ8y-lYv.js";import{C as Is}from"./circle-help-DH0PhjCT.js";import{L as qs}from"./link-2-BYrkkW_z.js";import{L as Es}from"./lock-C4IoD0ep.js";import{u as ht}from"./useMutation-C1UN62nU.js";import{R as is}from"./rotate-ccw-Bj7jRuUH.js";import{F as Ps}from"./folder-open-Ba6XBc1I.js";import{F as zs}from"./folder-D8Nmwg4M.js";import{c as _e,T as ft,a as _t,b as Oe,d as yt,e as ee}from"./table-CTm7mt6O.js";import{u as Ms,T as Vs}from"./TablePaginationFooter-Brq27wj-.js";import{P as Ks,a as Os,b as $s}from"./popover-CQgjLlkx.js";import{F as Gs}from"./filter-JbNBtMLY.js";import{R as Et}from"./refresh-cw-BxKWYM84.js";import{f as ns}from"./format-CpEgwowc.js";import{u as Bs,a as Pt,s as Us,K as Qs,P as Hs,D as Ws,c as Js,S as Ys,v as Zs,b as Xs,C as ea,d as ta}from"./data-grid-BglESalw.js";import{u as sa}from"./useAIFieldPrompts-B0IgSbLh.js";import{c as zt}from"./toast-utils-DbfcVDp6.js";import{S as aa}from"./save-7-OHGy_p.js";import{u as ra}from"./useChannelListener-EBpa4lO_.js";import{C as ia}from"./chevron-left-C6mkHNrW.js";import{S as na}from"./scroll-area-ejwojEUF.js";import{E as la}from"./excel-CPlAJqTR.js";import{b as st,d as oa,r as ca,s as da,U as ua}from"./excelHelpers-CZ_RS878.js";import{D as ls}from"./download-yfqQrhxH.js";import{C as pa}from"./circle-check-muHzTCkC.js";import{I as ma}from"./info-CMats5eS.js";import{C as ha}from"./circle-alert-BqRwdKSO.js";import{u as xa}from"./useOrgEntitlements-alOXMBXd.js";import{S as ga}from"./shield-check-CZN8d-nb.js";import{C as fa}from"./copy-CFeQEnPt.js";import{F as _a}from"./file-up-HapzQ6I-.js";import{b as ya,d as va}from"./dataModelExport-b0Au4uu_.js";import ba from"./BrandGuardPage-C1VLsY4e.js";import{S as Mt}from"./settings-D7Vikbun.js";import{P as ja}from"./plug-Bq3Sb3rg.js";import{C as Vt}from"./clipboard-check-Ddt5diI2.js";import{H as Kt}from"./history-Y1YHfrMP.js";import{F as Ot}from"./file-text-BDY5_BzP.js";import{T as Na}from"./tags-BX3Vqy0s.js";import{L as wa}from"./list-batvW8ed.js";import{R as ka}from"./radio-ek8BJOHi.js";import"./eventLogger-CNA3LMaL.js";import"./wand-sparkles-DHDh2tp5.js";import"./layers-CL85HQys.js";import"./tag-BF4Aq_gs.js";import"./en-US-Ca8fhmg7.js";import"./settings-2-ifeXNVik.js";import"./useOrgLimits-BeajuN3z.js";import"./useLocales-CsMUTv8f.js";/** 2 * @license lucide-react v0.462.0 - ISC 3 * 4 * This source code is licensed under the ISC license. 5 * See the LICENSE file in the root directory of this source tree. 6 */const Ca=vt("ArrowDownAZ",[["path",{d:"m3 16 4 4 4-4",key:"1co6wj"}],["path",{d:"M7 20V4",key:"1yoxec"}],["path",{d:"M20 8h-5",key:"1vsyxs"}],["path",{d:"M15 10V6.5a2.5 2.5 0 0 1 5 0V10",key:"ag13bf"}],["path",{d:"M15 14h5l-5 6h5",key:"ur5jdg"}]]);/** 7 * @license lucide-react v0.462.0 - ISC 8 * 9 * This source code is licensed under the ISC license. 10 * See the LICENSE file in the root directory of this source tree. 11 */const Sa=vt("ArrowLeftRight",[["path",{d:"M8 3 4 7l4 4",key:"9rb6wj"}],["path",{d:"M4 7h16",key:"6tx8e3"}],["path",{d:"m16 21 4-4-4-4",key:"siv7j2"}],["path",{d:"M20 17H4",key:"h6l3hr"}]]);/** 12 * @license lucide-react v0.462.0 - ISC 13 * 14 * This source code is licensed under the ISC license. 15 * See the LICENSE file in the root directory of this source tree. 16 */const os=vt("Ban",[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["path",{d:"m4.9 4.9 14.2 14.2",key:"1m5liu"}]]);/** 17 * @license lucide-react v0.462.0 - ISC 18 * 19 * This source code is licensed under the ISC license. 20 * See the LICENSE file in the root directory of this source tree. 21 */const Aa=vt("Key",[["path",{d:"m15.5 7.5 2.3 2.3a1 1 0 0 0 1.4 0l2.1-2.1a1 1 0 0 0 0-1.4L19 4",key:"g0fldk"}],["path",{d:"m21 2-9.6 9.6",key:"1j0ho8"}],["circle",{cx:"7.5",cy:"15.5",r:"5.5",key:"yqb3hr"}]]);/** 22 * @license lucide-react v0.462.0 - ISC 23 * 24 * This source code is licensed under the ISC license. 25 * See the LICENSE file in the root directory of this source tree. 26 */const Da=vt("Timer",[["line",{x1:"10",x2:"14",y1:"2",y2:"2",key:"14vaq8"}],["line",{x1:"12",x2:"15",y1:"14",y2:"11",key:"17fdiu"}],["circle",{cx:"12",cy:"14",r:"8",key:"1e1u0o"}]]);function cs(s){const l=je({queryKey:["pim-scope-collisions",s],enabled:!!s,queryFn:async()=>{const{data:f,error:b}=await U.rpc("pim_attribute_scope_collisions",{p_org_id:s});if(b)throw b;return f??[]}}),_=l.data??[],i=new Set;for(const f of _)i.add(f.global_attr_id),i.add(f.scoped_attr_id);const g=new Map;for(const f of _)g.set(f.matched_value,f);return{collisions:_,collidingIds:i,byLabel:g,isLoading:l.isLoading}}const Ra=[{value:"text",label:"Text"},{value:"richtext",label:"Rich Text"},{value:"number",label:"Number"},{value:"bool",label:"Boolean"},{value:"date",label:"Date"},{value:"list",label:"List"},{value:"json",label:"JSON"},{value:"array",label:"Array"},{value:"feature_bullets",label:"Feature Bullets"},{value:"table",label:"Table"}],$t={attribute_id:null,key:"",label:"",data_type:"text",description:"",default_value:"",field_group_id:null,list_id:null,category_scoped:!1,is_translatable:!1,is_required_for_publish:!1,is_filterable:!1,is_sortable:!1,is_multi_select:!1,is_readonly:!1,formula:"",display_lines:1};function Fa(s){return{attribute_id:s.id,key:s.key,label:s.label||"",data_type:s.data_type,description:s.description??"",default_value:s.default_value??"",field_group_id:s.field_group_id,list_id:s.list_id,category_scoped:s.category_scoped,is_translatable:s.is_translatable,is_required_for_publish:s.is_required_for_publish,display_lines:s.display_lines??
261,is_filterable:s.is_filterable,is_sortable:s.is_sortable,is_multi_select:s.is_multi_select,is_readonly:s.is_readonly,formula:s.formula||""}}function ds({open:s,onOpenChange:l,attribute:_,orgId:i,repositoryKey:g,lists:f,fieldGroups:b,onSaved:I,defaultCategoryScoped:T=!1,defaultFieldGroupId:o=null}){const w=Ge(),[d,m]=c.useState($t),[S,F]=c.useState(!1),[P,V]=c.useState(""),[q,y]=c.useState(""),[t,p]=c.useState([]),[D,h]=c.useState(""),[M,Q]=c.useState(!1);c.useEffect(()=>{s&&(m(_?Fa(_):{...$t,category_scoped:T,field_group_id:o}),V(""),y(""),p([]),h(""))},[s,_]);const E=async()=>{const r=P.trim();if(!r||!i)return;const{data:j,error:n}=await U.rpc("pim_upsert_field_group",{p_org_id:i,p_repository_key:g,p_name:r});if(n||!(j!=null&&j.success)){L.error("Failed to create field group");return}await w.invalidateQueries({queryKey:["pim-schema"]}),m(R=>({...R,field_group_id:j.field_group_id})),V(""),L.success(`Field group "${r}" created`)},X=async()=>{const r=q.trim();if(!(!r||!i)){Q(!0);try{const{data:j,error:n}=await U.rpc("pim_upsert_list",{p_org_id:i,p_name:r});if(n||!(j!=null&&j.success))throw new Error("list");const R=j.list_id;for(let a=0;a<t.length;a++)await U.rpc("pim_upsert_list_value",{p_org_id:i,p_list_id:R,p_value:t[a],p_label:t[a],p_display_order:a});await w.invalidateQueries({queryKey:["pim-lists"]}),m(a=>({...a,list_id:R})),y(""),p([]),L.success(`List "${r}" created`)}catch{L.error("Failed to create list")}Q(!1)}},x=async()=>{if(!i)return;const r=d.key.trim().toLowerCase().replace(/\s+/g,"_");if(!r){L.error("Attribute key required");return}if(d.data_type==="list"&&!d.list_id){L.error("Select or create a list for list-type attributes");return}F(!0);try{const{data:j,error:n}=await U.rpc("pim_upsert_attribute",{p_org_id:i,p_repository_key:g,p_key:r,p_label:d.label||null,p_data_type:d.data_type,p_field_group_id:d.field_group_id,p_list_id:d.data_type==="list"?d.list_id:null,p_category_scoped:d.category_scoped,p_is_translatable:d.is_translatable,p_is_required_for_publish:d.is_required_for_publish,p_display_order:null,p_formula:d.formula.trim()||null,p_attribute_id:d.attribute_id,p_is_filterable:d.is_filterable,p_is_sortable:d.is_sortable,p_description:d.description.trim()||null,p_default_value:d.default_value.trim()||null,p_multi_select:d.is_multi_select,p_display_lines:d.display_lines,p_is_readonly:d.is_readonly});if(n||!(j!=null&&j.success))throw new Error((j==null?void 0:j.error)||"save");I(),l(!1),L.success(d.attribute_id?"Attribute updated":"Attribute created")}catch(j){const n=j instanceof Error?j.message:"Failed to save attribute";L.error(n==="save"?"Failed to save attribute":n)}F(!1)};return e.jsx(Ee,{open:s,onOpenChange:l,children:e.jsxs(Pe,{className:"w-[500px] sm:max-w-[500px] overflow-y-auto",children:[e.jsx(ze,{children:e.jsx(Me,{children:d.attribute_id?"Edit Attribute":"New Attribute"})}),e.jsxs("div",{className:"space-y-4 py-4",children:[e.jsxs("div",{className:"space-y-1",children:[e.jsx(W,{className:"text-xs font-semibold uppercase text-muted-foreground",children:"Label"}),e.jsx(te,{value:d.label,onChange:r=>{const j=r.target.value;m(n=>({...n,label:j,...n.attribute_id?{}:{key:j.trim().toLowerCase().replace(/\s+/g,"_").replace(/[^a-z0-9_]/g,"")}}))},placeholder:"e.g. Waterproof Rating"})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx(W,{className:"text-xs font-semibold uppercase text-muted-foreground",children:"Key"}),e.jsx(te,{value:d.key,disabled:!!d.attribute_id,onChange:r=>m(j=>({...j,key:r.target.value})),placeholder:"waterproof_rating",className:"font-mono text-sm"}),!d.attribute_id&&e.jsx("p",{className:"text-[10px] text-muted-foreground",children:"Auto-generated from label. Cannot change after creation."})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx(W,{className:"text-xs font-semibold uppercase text-muted-foreground",children:"Description"}),e.jsx(te,{value:d.description,onChange:r=>m(j=>({...j,description:r.target.value})),placeholder:"What does this field mean?"}),e.jsx("p",{className:"text-[10px] text-muted-foreground",children:"Helps CC and users understand this field's purpose."})]}),e.jsx("div",{className:"border-t pt-4"}),e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsxs("div",{className:"space-y-1",children:[e.jsx(W,{className:"text-xs font-semibold uppercase text-muted-foreground",children:"Data Type"}),e.jsxs(re,{value:d.data_type,onValueChange:r=>m(j=>({...j,data_type:r,list_id:r==="list"?j.list_id:null,is_multi_select:r==="list"?j.is_multi_select:!1})),children:[e.jsx(ie,{children:e.jsx(ne,{})}),e.jsx(le,{children:Ra.map(r=>e.jsx(J,{value:r.value,children:r.label},r.value))})]})]}),d.data_type==="list"&&e.jsxs("div",{className:"space-y-1",children:[e.jsx(W,{className:"text-xs font-semibold uppercase text-muted-foreground",children:"List"}),e.jsxs(re,{value:d.list_id||"__none",onValueChange:r=>m(j=>({...j,list_id:r==="__none"?null:r})),children:[e.jsx(ie,{children:e.jsx(ne,{placeholder:"Selectâ¦"})}),e.jsxs(le,{children:[e.jsx(J,{value:"__none",children:"â Select â"}),(f??[]).map(r=>
26e.jsxs(J,{value:r.id,children:[r.name,typeof r.value_count=="number"?` (${r.value_count})`:""]},r.id))]})]})]})]}),d.data_type==="list"&&e.jsxs("div",{className:"border border-dashed rounded p-2.5 space-y-2",children:[e.jsx(te,{value:q,onChange:r=>y(r.target.value),placeholder:"New list name",className:"h-7 text-xs"}),t.length>0&&e.jsx("div",{className:"flex flex-wrap gap-1",children:t.map((r,j)=>e.jsxs(se,{variant:"secondary",className:"text-[10px] gap-1",children:[r,e.jsx("button",{onClick:()=>p(n=>n.filter((R,a)=>a!==j)),children:e.jsx(kt,{className:"h-2 w-2"})})]},j))}),e.jsxs("div",{className:"flex gap-1",children:[e.jsx(te,{value:D,onChange:r=>h(r.target.value),placeholder:"Add value",className:"h-7 text-xs",onKeyDown:r=>{r.key==="Enter"&&(r.preventDefault(),D.trim()&&(p(j=>[...j,D.trim()]),h("")))}}),e.jsx(N,{variant:"outline",size:"sm",className:"h-7 px-2",onClick:()=>{D.trim()&&(p(r=>[...r,D.trim()]),h(""))},children:e.jsx(Ne,{className:"h-3 w-3"})})]}),e.jsx(N,{size:"sm",variant:"outline",className:"w-full h-7 text-xs",disabled:M||!q.trim(),onClick:X,children:"Create List"})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsxs("div",{className:"space-y-1",children:[e.jsx(W,{className:"text-xs font-semibold uppercase text-muted-foreground",children:"Field Group"}),e.jsxs(re,{value:d.field_group_id||"__none",onValueChange:r=>m(j=>({...j,field_group_id:r==="__none"?null:r})),children:[e.jsx(ie,{children:e.jsx(ne,{placeholder:"Ungrouped"})}),e.jsxs(le,{children:[e.jsx(J,{value:"__none",children:"Ungrouped"}),b.map(r=>e.jsx(J,{value:r.id,children:r.name},r.id))]})]}),e.jsxs("div",{className:"flex gap-1 mt-1",children:[e.jsx(te,{value:P,onChange:r=>V(r.target.value),placeholder:"New group name",className:"h-7 text-xs",onKeyDown:r=>{r.key==="Enter"&&(r.preventDefault(),E())}}),e.jsx(N,{variant:"outline",size:"sm",className:"h-7 px-2",disabled:!P.trim(),onClick:E,children:e.jsx(Ne,{className:"h-3 w-3"})})]})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx(W,{className:"text-xs font-semibold uppercase text-muted-foreground",children:"Default Value"}),e.jsx(te,{value:d.default_value,onChange:r=>m(j=>({...j,default_value:r.target.value})),placeholder:"Optional"})]})]}),e.jsx("div",{className:"border-t pt-4"}),e.jsxs("div",{children:[e.jsx(W,{className:"text-xs font-semibold uppercase text-muted-foreground mb-3 block",children:"Flags"}),e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("span",{className:"text-sm",children:"Required for publish"}),e.jsx(Ce,{checked:d.is_required_for_publish,onCheckedChange:r=>m(j=>({...j,is_required_for_publish:r}))})]}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex flex-col",children:[e.jsx("span",{className:"text-sm",children:"Read-only"}),e.jsx("span",{className:"text-[10px] text-muted-foreground",children:"Value is shown but cannot be edited in the grid or PDP (system-managed fields)."})]}),e.jsx(Ce,{checked:d.is_readonly,onCheckedChange:r=>m(j=>({...j,is_readonly:r}))})]}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("span",{className:"text-sm",children:"Translatable"}),e.jsx(Ce,{checked:d.is_translatable,onCheckedChange:r=>m(j=>({...j,is_translatable:r}))})]}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("span",{className:"text-sm",children:"Filterable in grid"}),e.jsx(Ce,{checked:d.is_filterable,onCheckedChange:r=>m(j=>({...j,is_filterable:r}))})]}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("span",{className:"text-sm",children:"Sortable in grid"}),e.jsx(Ce,{checked:d.is_sortable,onCheckedChange:r=>m(j=>({...j,is_sortable:r}))})]}),(d.data_type==="text"||d.data_type==="richtext")&&e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("span",{className:"text-sm",children:"Display lines"}),e.jsx("select",{value:d.display_lines,onChange:r=>m(j=>({...j,display_lines:parseInt(r.target.value)})),className:"text-sm border rounded px-2 py-1 bg-background w-20",children:[1,2,3,4,5,6,8,10].map(r=>e.jsxs("option",{value:r,children:[r," line",r>1?"s":""]},r))})]}),(d.data_type==="list"||d.data_type==="array")&&e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("span",{className:"text-sm",children:"Multi-select"}),e.jsx(Ce,{checked:d.is_multi_select,onCheckedChange:r=>m(j=>({...j,is_multi_select:r}))})]})]})]}),e.jsx("div",{className:"border-t pt-4"}),e.jsxs("div",{children:[e.jsx(W,{className:"text-xs font-semibold uppercase text-muted-foreground mb-3 block",children:"Scope"}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("span",{className:"text-sm",children:"Category-scoped"}),e.jsx(Ce,{checked:d.category_scoped,onCheckedChange:r=>m(j=>({...j,category_scoped:r}))})]}),d.category_scoped&&e.jsx("p",{className:"text-[10px] text-muted-foreground mt-1.5 pl-1",children:"Assign this attribute to specific categories in the Categories tab after creation."})]}),e.jsx("div",{className:"border-t pt-4"}),e.jsxs("div",{className:"space-y-1",children:[e.jsx(W,{className:"text-xs font-semibold uppercase text-muted-foreground",children:"Formula (optional)"}),e.jsx(Lt,{value:d.formula,onChange:r=>m(j=>({...j,formula:r.target.value})),placeholder:'e.g. CONCAT(vendor, " ", title)',rows:2,className:"font-mono text-xs"}),e.jsx("p",{className:"text-[10px] text-muted-foreground",children:"Server-side computed on save. Cycles rejected automatically."})]})]}),e.jsxs(qe,{className:"border-t pt-4",children:[e.jsx(N,{variant:"outline",onClick:()=>l(!1),children:"Cancel"}
26),e.jsx(N,{onClick:x,disabled:S||!d.key.trim(),children:S?"Savingâ¦":d.attribute_id?"Save":"Create Attribute"})]})]})})}function Ta({repositoryKey:s}){var pe,De;const{currentOrg:l}=Se(),_=l==null?void 0:l.id,{collidingIds:i}=cs(_),g=Ge(),f=Xe(s),[b,I]=c.useState(new Set),[T,o]=c.useState(!1),[w,d]=c.useState(null),[m,S]=c.useState(null),[F,P]=c.useState(null),[V,q]=c.useState(null),[y,t]=c.useState(new Set),[p,D]=c.useState(!1),[h,M]=c.useState({id:null,name:""}),[Q,E]=c.useState(!1),[X,x]=c.useState(null),[r,j]=c.useState(null),[n,R]=c.useState(null),[a,k]=c.useState(null),Y=()=>{g.invalidateQueries({queryKey:["pim-schema"]}),g.invalidateQueries({queryKey:["pim-lists"]}),g.invalidateQueries({queryKey:["pim-list-values-expanded"]})},Z=async(u,H,B)=>{if(!_)return;const de=f.attributes.find(Fe=>Fe.id===u);if(!de)return;const ve=de.field_group_id??null,Re=Fe=>f.attributes.filter(we=>(we.field_group_id??null)===Fe&&we.id!==u).sort((we,tt)=>we.display_order-tt.display_order||(we.label||we.key).localeCompare(tt.label||tt.key)).map(we=>we.id),ge=Re(H),be=B==null?ge.length:Math.max(0,Math.min(B,ge.length));ge.splice(be,0,u);const z=ge.map((Fe,we)=>({id:Fe,display_order:we+1,...Fe===u?{field_group_id:H??""}:{}}));ve!==H&&Re(ve).forEach((Fe,we)=>z.push({id:Fe,display_order:we+1}));const{error:Ie}=await U.rpc("pim_reorder_attributes",{p_org_id:_,p_updates:z});if(Ie){L.error("Failed to reorder attribute");return}Y(),L.success("Attribute reordered")},A=(u,H)=>Z(u,H),{data:G}=je({queryKey:["pim-lists",_],enabled:!!_,queryFn:async()=>{const{data:u,error:H}=await U.rpc("pim_get_lists",{p_org_id:_});if(H)throw H;return u??[]}}),C=Array.from(y),ye=je({queryKey:["pim-list-values-expanded",_,C.sort().join(",")],enabled:!!_&&C.length>0,queryFn:async()=>{const u={};for(const H of C){const{data:B}=await U.rpc("pim_get_list_values",{p_list_id:H});B&&(u[H]=B)}return u}}).data??{};c.useMemo(()=>new Map(f.fieldGroups.map(u=>[u.id,u])),[f.fieldGroups]);const ce=c.useMemo(()=>f.attributes.filter(u=>!u.category_scoped),[f.attributes]),Ae=c.useMemo(()=>{const u={};for(const B of ce){const ve=B.field_group_id??"__ungrouped";(u[ve]??(u[ve]=[])).push(B)}Object.values(u).forEach(B=>B.sort((de,ve)=>de.display_order-ve.display_order));const H=[];for(const B of f.fieldGroups)u[B.id]&&H.push({id:B.id,name:B.name,attrs:u[B.id],order:B.display_order});u.__ungrouped&&H.push({id:null,name:"Ungrouped",attrs:u.__ungrouped,order:999999});for(const B of f.fieldGroups)u[B.id]||H.push({id:B.id,name:B.name,attrs:[],order:B.display_order});return H.sort((B,de)=>B.order-de.order)},[ce,f.fieldGroups]),O=async(u,H)=>{const B=Ae.filter(be=>be.id!==null),de=B.findIndex(be=>be.id===u);if(de<0||H==="up"&&de===0||H==="down"&&de===B.length-1)return;const ve=H==="up"?de-1:de+1,Re=[...B];[Re[de],Re[ve]]=[Re[ve],Re[de]];const ge=Re.map((be,z)=>({id:be.id,display_order:z+1}));await U.rpc("pim_reorder_field_groups",{p_org_id:l==null?void 0:l.id,p_updates:ge}),g.invalidateQueries({queryKey:["pim-schema"]})},ue=async(u,H)=>{if(!(l!=null&&l.id)||u===H)return;const B=Ae.filter(be=>be.id!==null).map(be=>be.id),de=B.indexOf(u),ve=B.indexOf(H);if(de<0||ve<0)return;B.splice(de,1),B.splice(ve,0,u);const Re=B.map((be,z)=>({id:be,display_order:z+1})),{error:ge}=await U.rpc("pim_reorder_field_groups",{p_org_id:l.id,p_updates:Re});if(ge){L.error("Failed to reorder group");return}g.invalidateQueries({queryKey:["pim-schema"]}),L.success("Group reordered")},xe=u=>I(H=>{const B=new Set(H);return B.has(u)?B.delete(u):B.add(u),B}),Ve=u=>t(H=>{const B=new Set(H);return B.has(u)?B.delete(u):B.add(u),B}),Je=u=>{d(null),S(u??null),o(!0)},bt=u=>{d(u),S(null),o(!0)},et=async()=>{const u=h.name.trim();if(!(!u||!_)){E(!0);try{const H={p_org_id:_,p_repository_key:s,p_name:u};h.id&&(H.p_field_group_id=h.id);const{data:B,error:de}=await U.rpc("pim_upsert_field_group",H);if(de||!(B!=null&&B.success)){L.error("Failed to save field group");return}Y(),D(!1),L.success(h.id?`Renamed to "${u}"`:`Field group "${u}" created`)}catch{L.error("Failed to save field group")}E(!1)}},Le=async()=>{if(!X)return;const{error:u}=await U.rpc("pim_delete_field_group",{p_field_group_id:X.id});if(u){L.error("Failed to delete field group");return}Y(),L.success(`Field group "${X.name}" deleted`),x(null)},v=async u=>{P(u),q(null);const{data:H}=await U.rpc("pim_get_attribute_delete_impact",{p_attribute_id:u.id});q(H)},K=async()=>
26{if(!F)return;const{data:u,error:H}=await U.rpc("pim_delete_attribute",{p_attribute_id:F.id});if(H||!(u!=null&&u.success)){L.error((u==null?void 0:u.message)||"Failed to delete");return}Y(),L.success(`Deleted "${F.label||F.key}" (${u.values_destroyed} values removed)`),P(null),q(null)},ae=V&&(V.is_variant_axis||((pe=V.formula_refs)==null?void 0:pe.length)>0),oe=u=>{var H;return u?((H=G==null?void 0:G.find(B=>B.id===u))==null?void 0:H.name)??null:null};return f.isLoading?e.jsx("div",{className:"py-8 text-center text-sm text-muted-foreground",children:"Loadingâ¦"}):e.jsxs("div",{className:"space-y-0",children:[e.jsxs("div",{className:"px-4 py-2.5 text-xs text-muted-foreground border-b",children:[ce.length," attributes across ",f.fieldGroups.length," groups.",(()=>{const u=ce.filter(H=>!H.field_group_id).length;return u>0?` ${u} are ungrouped.`:""})()]}),e.jsxs("div",{className:"flex items-center gap-2 px-4 py-1.5 border-b bg-muted/10 flex-wrap",children:[f.fieldGroups.sort((u,H)=>u.display_order-H.display_order).map(u=>e.jsxs("span",{className:"inline-flex items-center gap-1 px-2 py-0.5 rounded border bg-background text-xs",children:[u.name,e.jsx("span",{className:"text-muted-foreground/60 text-[10px]",children:ce.filter(H=>H.field_group_id===u.id).length})]},u.id)),ce.filter(u=>!u.field_group_id).length>0&&e.jsxs("span",{className:"inline-flex items-center gap-1 px-2 py-0.5 rounded border border-dashed bg-background text-xs text-muted-foreground",children:["Ungrouped",e.jsx("span",{className:"text-[10px]",children:ce.filter(u=>!u.field_group_id).length})]}),e.jsxs(N,{variant:"ghost",size:"sm",className:"h-6 text-xs text-primary gap-1",onClick:()=>{M({id:null,name:""}),D(!0)},children:[e.jsx(Ne,{className:"h-3 w-3"})," New Group"]})]}),Ae.map((u,H)=>{const B=Ae.filter(z=>z.id!==null),de=B.findIndex(z=>z.id===u.id),ve=de===0,Re=de===B.length-1,ge=u.id??"__ungrouped",be=b.has(ge);return e.jsxs("div",{className:"border-b last:border-b-0",children:[e.jsxs("div",{role:"button",tabIndex:0,draggable:!!u.id,onDragStart:z=>{u.id&&(z.dataTransfer.setData("group-id",u.id),z.dataTransfer.effectAllowed="move",k(u.id))},onDragEnd:()=>{k(null),R(null)},onDragOver:z=>{!u.id||!z.dataTransfer.types.includes("group-id")||(z.preventDefault(),z.dataTransfer.dropEffect="move",R(ge))},onDrop:z=>{if(!u.id||!z.dataTransfer.types.includes("group-id"))return;z.preventDefault();const Ie=z.dataTransfer.getData("group-id");Ie&&Ie!==u.id&&ue(Ie,u.id),k(null),R(null)},className:he("flex items-center gap-2 w-full px-4 py-3 text-left group cursor-pointer select-none","bg-muted/70 hover:bg-muted border-y border-border/60",a===u.id&&"opacity-40",n===ge&&a&&a!==u.id&&"ring-2 ring-primary/40 ring-inset"),onClick:()=>xe(ge),onKeyDown:z=>{(z.key==="Enter"||z.key===" ")&&(z.preventDefault(),xe(ge))},children:[u.id&&e.jsx(wt,{className:"h-4 w-4 text-muted-foreground/50 cursor-grab shrink-0"}),be?e.jsx(Tt,{className:"h-4 w-4 text-muted-foreground shrink-0"}):e.jsx(Jt,{className:"h-4 w-4 text-muted-foreground shrink-0"}),e.jsx("span",{className:"text-sm font-bold uppercase tracking-wider text-foreground",children:u.name}),e.jsx("span",{className:"text-xs font-semibold text-muted-foreground/70 tabular-nums",children:u.attrs.length}),u.id&&e.jsxs("div",{className:"ml-auto flex gap-1 opacity-0 group-hover:opacity-100",children:[e.jsx(N,{variant:"ghost",size:"icon",className:"h-5 w-5",title:"Move group up",disabled:ve,onClick:z=>{z.stopPropagation(),u.id&&O(u.id,"up")},children:e.jsx(At,{className:"h-2.5 w-2.5"})}),e.jsx(N,{variant:"ghost",size:"icon",className:"h-5 w-5",title:"Move group down",disabled:Re,onClick:z=>{z.stopPropagation(),u.id&&O(u.id,"down")},children:e.jsx(es,{className:"h-2.5 w-2.5"})}),e.jsx(N,{variant:"ghost",size:"icon",className:"h-5 w-5",title:"Rename",onClick:z=>{z.stopPropagation(),M({id:u.id,name:u.name}),D(!0)},children:e.jsx(We,{className:"h-2.5 w-2.5"})}),e.jsx(N,{variant:"ghost",size:"icon",className:"h-5 w-5 text-destructive",title:"Delete group (attributes move to Ungrouped)",onClick:z=>{z.stopPropagation(),u.id&&x({id:u.id,name:u.name})},children:e.jsx($e,{className:"h-2.5 w-2.5"})})]})]}),!be&&e.jsxs("div",{onDragOver:z=>{z.dataTransfer.types.includes("attr-id")&&(z.preventDefault(),z.dataTransfer.dropEffect="move",R(ge))},onDragLeave:z=>{z.currentTarget.contains(z.relatedTarget)||R(null)},onDrop:z=>{z.preventDefault();const Ie=z.dataTransfer.getData("attr-id");Ie&&A(Ie,u.id),R(null),j(null)},className:he("grid grid-cols-2",n===ge&&r&&"bg-primary/5 ring-1 ring-primary/20 ring-inset"),children:[u.attrs.map((z,Ie)=>{var It;const Fe=oe(z.list_id),we=z.authored_by!=="human"||!z.is_pinned,tt=z.list_id&&y.has(z.list_id);return e.jsxs("div",{className:he(tt&&"col-span-2"),children:[e.jsxs("div",{className:he("grid items-center px-3 py-2 hover:bg-accent/50 group",r===z.id&&"opacity-40",Math.floor(Ie/2)%2===0?"bg-black/[0.04] dark:bg-white/[0.04]":""),style:{gridTemplateColumns:"16px 1fr 56px 100px 28px 52px"},draggable:!0,onDragStart:fe=>{fe.dataTransfer.setData("attr-id",z.id),fe.dataTransfer.effectAllowed="move",j(z.id)},onDragEnd:()=>j(null),onDragOver:fe=>{fe.dataTransfer.types.includes("attr-id")&&(fe.preventDefault(),fe.stopPropagation(),fe.dataTransfer.dropEffect="move",R(ge))},onDrop:fe=>{if(!fe.dataTransfer.types.includes("attr-id"))return;fe.preventDefault(),fe.stopPropagation();const mt=fe.dataTransfer.getData("attr-id");mt&&mt!==z.id&&Z(mt,u.id,Ie),R(null),j(null)}
26,children:[e.jsx(wt,{className:"h-3 w-3 text-muted-foreground/30 cursor-grab"}),e.jsxs("span",{className:"text-sm font-medium truncate min-w-0 pr-2 flex items-center gap-1.5",children:[e.jsx("span",{className:"truncate",children:z.label||z.key}),i.has(z.id)&&e.jsx("span",{title:`"${z.label}" also exists as a category-scoped attribute. Review which you intend â this is informational only.`,className:"shrink-0 text-[10px] leading-none px-1.5 py-0.5 rounded border border-amber-400/60 text-amber-600 dark:text-amber-400",children:"also category-scoped"})]}),e.jsx("span",{className:"text-[11px] text-muted-foreground",children:z.data_type}),e.jsx("span",{className:"text-[11px] text-primary truncate",children:z.list_id&&Fe?e.jsx("button",{className:"hover:underline truncate",onClick:()=>Ve(z.list_id),children:Fe}):null}),e.jsxs("span",{className:"text-center",children:[z.is_required_for_publish&&e.jsx("span",{className:"text-[9px] font-semibold px-1 rounded bg-destructive/10 text-destructive",children:"req"}),!z.is_required_for_publish&&z.formula&&e.jsx("span",{className:"text-[9px] font-semibold px-1 rounded bg-purple-100 text-purple-700 dark:bg-purple-900/30 dark:text-purple-400",children:"f(x)"}),!z.is_required_for_publish&&!z.formula&&we&&e.jsx("span",{className:he("text-[9px] font-semibold px-1 rounded",z.authored_by==="agent"?"bg-purple-100 text-purple-700 dark:bg-purple-900/30 dark:text-purple-400":"bg-primary/10 text-primary"),children:z.authored_by==="agent"?"AI":"imp"})]}),e.jsxs("div",{className:"flex justify-end gap-0.5 opacity-0 group-hover:opacity-100",children:[e.jsx(N,{variant:"ghost",size:"icon",className:"h-6 w-6",onClick:()=>bt(z),title:"Edit",children:e.jsx(We,{className:"h-3 w-3"})}),e.jsx(N,{variant:"ghost",size:"icon",className:"h-6 w-6 text-destructive",onClick:()=>v(z),title:"Delete",children:e.jsx($e,{className:"h-3 w-3"})})]})]}),tt&&e.jsxs("div",{className:"mx-4 ml-10 mb-2 p-2 bg-muted/30 rounded border-l-2 border-primary",children:[e.jsx("div",{className:"flex items-center justify-between mb-1.5",children:e.jsxs("span",{className:"text-[11px] font-semibold text-muted-foreground",children:[Fe," â ",((It=ye==null?void 0:ye[z.list_id])==null?void 0:It.length)??"â¦"," values"]})}),e.jsx("div",{className:"flex flex-wrap gap-1",children:((ye==null?void 0:ye[z.list_id])??[]).sort((fe,mt)=>fe.display_order-mt.display_order).map(fe=>e.jsx("span",{className:"inline-flex items-center gap-1 px-2 py-0.5 bg-background border rounded text-xs",children:fe.label||fe.value},fe.value))})]})]},z.id)}),e.jsx("div",{className:"col-span-2 px-4 py-1.5",children:e.jsxs("button",{className:"text-xs text-primary hover:underline flex items-center gap-1",onClick:()=>Je(u.id),children:[e.jsx(Ne,{className:"h-3 w-3"}),"Add attribute"]})})]})]},ge)}),Ae.length===0&&e.jsxs("div",{className:"py-12 text-center",children:[e.jsx("p",{className:"text-sm text-muted-foreground mb-2",children:"No attributes defined for this entity type."}),e.jsxs(N,{size:"sm",onClick:()=>Je(),children:[e.jsx(Ne,{className:"h-3.5 w-3.5 mr-1.5"}),"Create First Attribute"]})]}),e.jsx(ds,{open:T,onOpenChange:o,attribute:w,orgId:_,repositoryKey:s,lists:G,fieldGroups:f.fieldGroups,defaultFieldGroupId:m,onSaved:Y}),e.jsx(it,{open:!!F,onOpenChange:u=>{u||(P(null),q(null))},children:e.jsxs(nt,{children:[e.jsxs(lt,{children:[e.jsxs(ot,{className:"flex items-center gap-2",children:[e.jsx(xt,{className:"h-5 w-5 text-destructive"}),"Delete â",(F==null?void 0:F.label)||(F==null?void 0:F.key),"â?"]}),e.jsx(ct,{asChild:!0,children:e.jsx("div",{className:"space-y-2",children:V?ae?e.jsx("span",{className:"text-destructive",children:V.is_variant_axis?"This attribute is a variant option. Remove it as a variant option before deleting.":`Referenced by formula on: ${(De=V.formula_refs)==null?void 0:De.map(u=>u.label).join(", ")}. Update those formulas first.`}):e.jsxs("span",{children:["This permanently deletes the attribute definition and"," ",e.jsx("strong",{children:V.value_count})," stored value(s) across ",e.jsx("strong",{children:V.record_count})," record(s). This cannot be undone."]}):e.jsx("span",{children:"Checking impactâ¦"})})})]}),e.jsxs(dt,{children:[e.jsx(ut,{children:"Cancel"}),e.jsx(pt,{className:"bg-destructive hover:bg-destructive/90",disabled:!V||!!ae,onClick:K,children:"Delete Permanently"})]})]})}),e.jsx(Ee,{open:p,onOpenChange:D,children:e.jsxs(Pe,{className:"w-[400px] sm:max-w-[400px]",children:[e.jsx(ze,{children:e.jsx(Me,{children:h.id?"Edit Field Group":"New Field Group"})}),e.jsx("div",{className:"space-y-4 py-6",children:e.jsxs("div",{className:"space-y-1",children:[e.jsx(W,{className:"text-xs font-semibold uppercase text-muted-foreground",children:"Name"}),e.jsx(te,{value:h.name,onChange:u=>M(H=>({...H,name:u.target.value})),placeholder:"e.g. Specs, Dimensions, Compliance",autoFocus:!0,onKeyDown:u=>{u.key==="Enter"&&(u.preventDefault(),et())}}),e.jsx("p",{className:"text-[10px] text-muted-foreground",children:"Field groups organize attributes into sections on the product detail page."})]})}),e.jsxs(qe,{className:"border-t pt-4",children:[e.jsx(N,{variant:"outline",onClick:()=>D(!1),children:"Cancel"}),e.jsx(N,{onClick:et,disabled:Q||!h.name.trim(),children:Q?"Savingâ¦":h.id?"Save":"Create Group"})]})]})}),e.jsx(it,{open:!!X,onOpenChange:u=>{u||x(null)},children:e.jsxs(nt,{children:[e.jsxs(lt,{children:[e.jsxs(ot,{className:"flex items-center gap-2",children:[e.jsx(xt,{className:"h-5 w-5 text-destructive"}),"Delete field group â",X==null?void 0:X.name,"â?"]}
26),e.jsx(ct,{children:"Attributes in this group will move to Ungrouped. No attribute data is deleted."})]}),e.jsxs(dt,{children:[e.jsx(ut,{children:"Cancel"}),e.jsx(pt,{className:"bg-destructive hover:bg-destructive/90",onClick:Le,children:"Delete Group"})]})]})})]})}const Dt=c.forwardRef(({className:s,...l},_)=>{const i=Array.isArray(l.value)?l.value.length:Array.isArray(l.defaultValue)?l.defaultValue.length:1;return e.jsxs(ss,{ref:_,className:he("relative flex w-full touch-none select-none items-center",s),...l,children:[e.jsx(Rs,{className:"relative h-2 w-full grow overflow-hidden rounded-full bg-background border border-border",children:e.jsx(Fs,{className:"absolute h-full bg-primary"})}),Array.from({length:i}).map((g,f)=>e.jsx(Ts,{className:"block h-5 w-5 rounded-full border-2 border-primary bg-background ring-offset-background transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:pointer-events-none disabled:opacity-50"},f))]})});Dt.displayName=ss.displayName;const Ke=[{value:"manual",label:"Manual"},{value:"review",label:"Review"},{value:"auto",label:"Auto-apply"}],Gt=[{value:"reactive",label:"Reactive"},{value:"proactive",label:"Proactive"}],Rt={proactivity:{key:"proactivity",agent:"*",section:"Activity",label:"Proactive scanning",kind:"activity_toggle",choices:Gt,help:"Reactive â the agent does nothing until you (or a pipeline) give it work; it never surprises you, but it also won't catch problems you didn't look for. Proactive â the agent scans your catalog on its own between tasks and surfaces issues it finds (missing descriptions, unlinked products, stale translations). Proactive costs a little more because you're paying for the searching, not just the fixing. Turn it on for catalogs you want actively watched; leave it off if you'd rather drive every action yourself."},generate_value:{key:"generate_value",agent:"augmentation",section:"AI writing",label:"AI content generation",kind:"approval_posture",choices:Ke,reviewCaption:"Review: generated content waits for your approval before it's saved.",help:"Controls what happens the moment the AI finishes writing a description, SEO field, or bullet. Manual â nothing is written until you ask for it each time. Review â the AI writes, but the text waits in your review queue and never touches a live product until you approve it; safest for customer-facing copy. Auto-apply â text is written straight to the product with no stop; fastest, but a bad generation goes live before you see it. Most stores start on Review and move high-volume, low-risk fields to Auto."},auto_configure:{key:"auto_configure",agent:"augmentation",section:"AI writing",label:"Auto-configure fields",kind:"approval_posture",choices:Ke,linkedBar:"auto_configure_confidence",reviewCaption:"Review: field setups the AI is confident about (above the bar) apply automatically; the rest wait for your approval.",help:"When the AI sets up how a field should be written (prompt, tone, content type) â deciding whether an incoming field matches one you already have or needs a new setup. Manual â you configure fields yourself. Review â high-confidence setups apply automatically; uncertain ones wait. Auto-apply â the AI configures fields on its own. A field's configuration shapes every value later generated for it, so start on Review."},auto_configure_confidence:{key:"auto_configure_confidence",agent:"augmentation",section:"AI writing",label:"Field-match confidence",kind:"confidence_threshold",isBar:!0,help:"Under Review, how sure the AI must be that an incoming field matches an existing attribute (rather than needing a new one) before it auto-configures without asking. Higher = only near-certain matches auto-apply; more setups wait for you."},categorize:{key:"categorize",agent:"augmentation",section:"Categorization",label:"Auto-categorization",kind:"approval_posture",choices:Ke,linkedBar:"categorize_confidence",reviewCaption:"Review: category matches above the bar apply automatically; the rest wait for your approval.",help:"What happens when the AI decides which category a product belongs in. Manual â you categorize yourself;
26 the AI won't. Review â confident matches (above the bar) apply automatically; the rest wait for you. Auto-apply â all picks apply immediately. Use Auto only once you trust the AI's category picks on your catalog."},categorize_confidence:{key:"categorize_confidence",agent:"augmentation",section:"Categorization",label:"Category match confidence",kind:"confidence_threshold",isBar:!0,help:"Under Review, the cutoff for auto-applying a category match. The AI scores how sure it is a product fits a category (0 = a guess, 1 = certain); matches at or above this bar apply automatically, below it wait for review. Raise it (e.g. 0.9) for only near-certain matches â fewer auto-categorizations, almost no wrong ones. Lower it (e.g. 0.6) to categorize more automatically at the cost of more mistakes."},categorize_can_create:{key:"categorize_can_create",agent:"augmentation",section:"Categorization",label:"New-category creation",kind:"approval_posture",choices:Ke,linkedBar:"categorize_can_create_confidence",reviewCaption:"Review: when the AI is confident (above the bar) that no existing category fits, it creates one automatically; otherwise it waits for your approval.",help:"Whether the categorizer may create a NEW category when no existing one matches â the same match-or-create decision as categorization, applied to the category itself. Manual â proposed new categories always wait for you (assign-only in practice). Review â when the AI is confident no existing category fits, it creates one automatically; borderline cases wait. Auto-apply â it creates whenever it judges no match exists. Creating a category reshapes your taxonomy, so most stores keep this on Manual until their tree is stable."},categorize_can_create_confidence:{key:"categorize_can_create_confidence",agent:"augmentation",section:"Categorization",label:"New-category confidence",kind:"confidence_threshold",isBar:!0,help:"Under Review, how sure the AI must be that NO existing category matches before it auto-creates a new one. Higher = creates new categories only when very certain nothing fits, so you get fewer accidental near-duplicate categories."},auto_link_match:{key:"auto_link_match",agent:"augmentation",section:"Linking",label:"Auto-linking",kind:"approval_posture",choices:Ke,linkedBar:"auto_link_confidence",reviewCaption:"Review: links above the bar apply automatically; the rest wait for your approval.",help:"What happens when the AI proposes links between products â accessories, cross-sells, variants. Manual â no automatic links. Review â confident links (above the bar) apply automatically; the rest wait. Auto-apply â all links attach immediately. A wrong link is visible to shoppers, so Review is the safe default; move to Auto only for link rules you've watched behave."},auto_link_confidence:{key:"auto_link_confidence",agent:"augmentation",section:"Linking",label:"Link match confidence",kind:"confidence_threshold",isBar:!0,help:"Under Review, how sure the AI must be before a link auto-applies. Matches below the bar wait for review. Raise it if loosely-related products are being linked; lower it if the AI is too conservative and misses obvious pairs."},generate_alt_text:{key:"generate_alt_text",agent:"image",section:"Alt text",label:"Alt-text generation",kind:"approval_posture",choices:Ke,reviewCaption:"Review: generated alt text waits for your approval before it's saved.",help:"What happens when the AI writes alt text for an image (used by screen readers and search engines). Manual â you write alt text yourself. Review â generated alt text waits for your approval before it's saved. Auto-apply â it's saved immediately. Alt text is lower-risk than customer-facing copy, so Auto is reasonable once you've seen the AI's descriptions are accurate."},dm_structural:{key:"dm_structural",agent:"data_model",section:"Structure changes",label:"Structural changes",kind:"approval_posture",choices:Ke,linkedBar:"dm_structural_confidence",reviewCaption:"Review: structural changes the agent is confident about (above the bar) apply automatically; the rest wait for your approval.",help:"Changes that alter what CAN EXIST in your model â adding or deleting attributes, adding/deleting/merging categories. This is the highest-blast-radius tier: a deleted attribute is gone from every product. Manual â every structural change waits for you. Review â changes the agent is confident enough about apply automatically; the rest wait. Auto-apply â all apply automatically. Most stores keep this the most cautious of the three."},dm_structural_confidence:{key:"dm_structural_confidence",agent:"data_model",section:"Structure changes",label:"Structural change confidence",kind:"confidence_threshold",isBar:!0,help:"Under Review, how sure the agent must be before a structural change auto-applies. Above the bar applies automatically; below it waits for you. Because structural changes are the most destructive, keep this high (e.g. 0.9) until you trust what you're seeing."},dm_semantic:{key:"dm_semantic",agent:"data_model",section:"Structure changes",label:"Meaning changes",kind:"approval_posture",choices:Ke,linkedBar:"dm_semantic_confidence",reviewCaption:"Review: meaning changes the agent is confident about (above the bar) a
26pply automatically; the rest wait for your approval.",help:"Changes to what an existing object MEANS or ENFORCES without adding or removing it â renaming or retyping attributes, renaming or moving categories, editing category-specific attributes. A rename can silently break references that point at the old name, so this tier sits between structural and value. Manual/Review/Auto as above."},dm_semantic_confidence:{key:"dm_semantic_confidence",agent:"data_model",section:"Structure changes",label:"Meaning change confidence",kind:"confidence_threshold",isBar:!0,help:"Under Review, how sure the agent must be before a meaning change (rename, retype, move) auto-applies. Above the bar applies automatically; below it waits for you."},dm_populative:{key:"dm_populative",agent:"data_model",section:"Structure changes",label:"Value changes",kind:"approval_posture",choices:Ke,linkedBar:"dm_populative_confidence",reviewCaption:"Review: value changes the agent is confident about (above the bar) apply automatically; the rest wait for your approval.",help:"Changes that FILL IN the existing shape â adding, editing, or removing dropdown values, and adding or removing category-specific attribute assignments. Lowest blast radius and most frequent, so this is the tier most stores loosen first. Manual/Review/Auto as above."},dm_populative_confidence:{key:"dm_populative_confidence",agent:"data_model",section:"Structure changes",label:"Value change confidence",kind:"confidence_threshold",isBar:!0,help:"Under Review, how sure the agent must be before a value change (dropdown values, category-scoped assignments) auto-applies. Above the bar applies automatically; below it waits for you."},dm_import_infer:{key:"dm_import_infer",agent:"data_model",section:"Imports",label:"Data-model import review",kind:"approval_posture",choices:Ke,reviewCaption:"Review: schema changes proposed by an import wait for your approval before they're applied.",help:"How much you review the schema changes a data-model IMPORT proposes â the new or changed attributes and categories inferred from an incoming file. This is independent of the three tier dials above, so you can hold an entire import for review even when your day-to-day edits run on Auto. Manual â the whole proposed changeset waits. Review â low-risk proposals apply, riskier ones wait. Auto-apply â the proposed changeset applies."},dm_taxonomy_scan:{key:"dm_taxonomy_scan",agent:"data_model",section:"Taxonomy monitoring",label:"Taxonomy monitoring",kind:"activity_toggle",choices:Gt,help:"Reactive â the Data Model agent only changes your schema when you ask. Proactive â about once a month it scans the Shopify product taxonomy and proposes attributes to add, change, or remove so your model keeps pace with the platform. Proposals still follow your Structural / Meaning / Value review settings above, so turning this on surfaces work; it doesn't bypass your approval gates."},margin:{key:"margin",agent:"pricing",section:"Margins",label:"Margin band",kind:"numeric_range",help:"The profit-margin band cost-based pricing keeps prices within. Min is the floor â prices won't be set below this margin even if a rule would; protects you from selling near cost. Max is the ceiling â caps how high the margin goes, so a cost drop doesn't silently inflate your price. Set both to define the range; leave them equal to pin a single target margin. This value is stored with the Pricing agent, not here â this panel just shows and edits it."}};function La(s){const l=Ge(),_=je({queryKey:["agent-settings",s],enabled:!!s,queryFn:async()=>{const{data:f,error:b}=await U.rpc("pim_get_settings",{p_org_id:s});if(b)throw b;return f??[]}}),i=c.useCallback(()=>{const f=_.data??[],b={},I=new Map;for(const T of f){const o=Rt[T.control_key];if(!o)continue;const w=T.target_kind==="agent"?T.target_ref:o.agent,d=`${w}::${T.control_key}`,m=I.get(d);if(m)m.value==null&&T.value!=null&&(m.value=T.value);else{const S={spec:o,agent:w,value:T.value};I.set(d,S),(b[w]||(b[w]=[])).push(S)}}return b},[_.data]),g=c.useCallback(async(f,b,I)=>{if(!s)throw new Error("No organization selected.");const T=Rt[b];if(!T)throw new Error(`Unknown control: ${b}`);const o=T.kind==="activity_toggle"?"agent":"capability",{error:w}=await U.rpc("pim_apply_control",{p_org_id:s,p_agent:f,p_control:b,p_value:I,p_scope:o});if(w)throw w;
26await l.invalidateQueries({queryKey:["agent-settings",s]})},[s,l]);return{isLoading:_.isLoading,error:_.error,controlsByAgent:i,setControl:g,refetch:_.refetch}}const jt={command_center:{name:"Command Center",description:"NLP router â the user-facing interface to all agents.",tier:0,icon:"bot"},data_model:{name:"Data Model",description:"Guards your schema â attributes, categories, and types.",tier:1,icon:"shield"},augmentation:{name:"Augmentation",description:"Writes descriptions, SEO, and bullets â and categorizes and links records.",tier:1,icon:"zap"},translation:{name:"Translation",description:"Manages translations and BrandGuard terms.",tier:1,icon:"zap"},validation:{name:"Validation",description:"Enforces data-quality rules across the catalog.",tier:1,icon:"shield"},image:{name:"Image",description:"Image quality checks and alt-text generation.",tier:1,icon:"eye"},pricing:{name:"Pricing",description:"Cost-based pricing calculations and rules.",tier:2,icon:"zap"},publish:{name:"Publish",description:"Manages publish nodes, rules, and product assignment.",tier:1,icon:"bot"},import:{name:"Import",description:"Handles file imports and ERP connections.",tier:1,icon:"bot"},reporting:{name:"Reporting",description:"Read-only catalog analysis and search.",tier:0,icon:"eye"},ops:{name:"Product Operations",description:"Product and variant lifecycle management.",tier:0,icon:"bot"}},Ia=["command_center","data_model","augmentation","translation","validation","image","pricing","publish","import","reporting","ops"],qa={bot:as,zap:rs,eye:Ls,shield:Yt};function Ft({text:s}){return e.jsxs(fs,{children:[e.jsx(_s,{asChild:!0,children:e.jsx("button",{type:"button",className:"inline-flex text-muted-foreground/60 hover:text-muted-foreground focus:outline-none focus-visible:ring-2 focus-visible:ring-ring rounded","aria-label":"What does this do?",children:e.jsx(Is,{className:"h-3.5 w-3.5"})})}),e.jsx(ys,{side:"left",className:"max-w-sm text-xs leading-relaxed",children:s})]})}function Ea({control:s,linkedBar:l,onChange:_,onChangeBar:i,saving:g}){const{spec:f,value:b}=s,I=l&&b==="review",T=f.key==="proactivity";return e.jsxs("div",{className:"space-y-1.5",children:[e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx(W,{className:"text-sm",children:f.label}),e.jsx(Ft,{text:f.help})]}),f.choices&&f.kind!=="consequence_tier"&&e.jsxs(re,{value:b??"",onValueChange:o=>_(o),disabled:g||T,children:[e.jsx(ie,{children:e.jsx(ne,{placeholder:"Platform default"})}),e.jsx(le,{children:f.choices.map(o=>e.jsx(J,{value:o.value,children:o.label},o.value))})]}),T&&e.jsx("p",{className:"mt-1 text-[11px] text-muted-foreground leading-relaxed",children:"Coming soon â proactive scanning isn't available yet. Agents act when you or a pipeline give them work."}),f.kind==="numeric_range"&&e.jsx(za,{value:b,onChange:_,saving:g}),I&&l&&e.jsxs("div",{className:"mt-2 rounded-md bg-muted/40 p-3 space-y-2",children:[f.reviewCaption&&e.jsx("p",{className:"text-[11px] text-muted-foreground leading-relaxed",children:f.reviewCaption}),e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx(W,{className:"text-xs text-muted-foreground",children:l.spec.label}),e.jsx(Ft,{text:l.spec.help})]}),e.jsx(Pa,{control:l,onChange:o=>i==null?void 0:i(o),saving:g})]}),!l&&f.reviewCaption&&b==="review"&&e.jsx("p",{className:"mt-1 text-[11px] text-muted-foreground leading-relaxed",children:f.reviewCaption})]})}function Pa({control:s,onChange:l,saving:_}){var T;const{spec:i,value:g}=s;if(i.kind==="confidence_threshold"){const o=typeof g=="number"?g:.7;return e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(Dt,{min:0,max:1,step:.05,value:[o],onValueChange:w=>l(w[0]),disabled:_,className:"flex-1"}),e.jsx("span",{className:"text-xs tabular-nums w-10 text-right",children:o.toFixed(2)})]})}const f=i.choices??[],b=Math.max(0,f.findIndex(o=>o.value===g)),I=b<0?0:b;return e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(Dt,{min:0,max:f.length-1,step:1,value:[I],onValueChange:o=>{var w;return l((w=f[o[0]])==null?void 0:w.value)},disabled:_,className:"flex-1"}),e.jsx("span",{className:"text-xs w-24 text-right",children:((T=f[I])==null?void 0:T.label)??"â"})]})}function za({value:s,onChange:l,saving:_}){const i=s&&typeof s=="object"?s:{},[g,f]=c.useState(i.min!=null?String(i.min):""),[b,I]=c.useState(i.max!=null?String(i.max):""),T=()=>{const o={};
26g!==""&&(o.min=Number(g)),b!==""&&(o.max=Number(b)),l(o)};return e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx("span",{className:"text-[11px] text-muted-foreground",children:"Min"}),e.jsx(te,{type:"number",value:g,onChange:o=>f(o.target.value),onBlur:T,disabled:_,className:"h-8 w-20",placeholder:"%"})]}),e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx("span",{className:"text-[11px] text-muted-foreground",children:"Max"}),e.jsx(te,{type:"number",value:b,onChange:o=>I(o.target.value),onBlur:T,disabled:_,className:"h-8 w-20",placeholder:"%"})]})]})}function Ma(){var y,t;const{currentOrg:s}=Se(),l=s==null?void 0:s.id,_=Ge(),{data:i}=je({queryKey:["catalog-agents",l],enabled:!!l,queryFn:async()=>{const{data:p,error:D}=await U.from("catalog_agents").select("id, agent_type, is_active").eq("org_id",l);if(D)throw D;return p??[]}}),g=La(l),f=c.useMemo(()=>g.controlsByAgent(),[g]),[b,I]=c.useState(null),[T,o]=c.useState(null),w=c.useMemo(()=>{const p=new Map;for(const D of i||[])p.set(D.agent_type,D);return p},[i]),d=()=>_.invalidateQueries({queryKey:["catalog-agents"]}),m=async p=>{var h;const{error:D}=await U.from("catalog_agents").update({is_active:!p.is_active}).eq("id",p.id);if(D){L.error("Couldn't change whether the agent runs. Try again.");return}d(),L.success(`${((h=jt[p.agent_type])==null?void 0:h.name)||p.agent_type} ${p.is_active?"disabled":"enabled"}`)},S=async(p,D,h)=>{o(D);try{await g.setControl(p,D,h),L.success("Setting saved")}catch(M){L.error(M instanceof Error?M.message:"Couldn't save that setting. Try again.")}finally{o(null)}},F=(i||[]).filter(p=>p.is_active).length,P=(i||[]).length,V=c.useMemo(()=>{const p=new Map;for(const D of Object.values(f))for(const h of D)h.spec.isBar&&p.set(h.spec.key,h);return p},[f]),q=p=>{const D=(f[p]||[]).filter(Q=>!Q.spec.isBar),h=Object.values(Rt).map(Q=>Q.key);D.sort((Q,E)=>h.indexOf(Q.spec.key)-h.indexOf(E.spec.key));const M=new Map;for(const Q of D){const E=M.get(Q.spec.section)||[];E.push(Q),M.set(Q.spec.section,E)}return Array.from(M.entries()).map(([Q,E])=>({section:Q,controls:E}))};return e.jsx(gs,{delayDuration:200,children:e.jsxs("div",{className:"space-y-0",children:[e.jsxs("div",{className:"px-4 py-2.5 text-xs text-muted-foreground border-b",children:[F," of ",P," agents active.",P-F>0?` ${P-F} disabled.`:""]}),Ia.map((p,D)=>{const h=jt[p];if(!h)return null;const M=w.get(p),Q=qa[h.icon],E=(f[p]||[]).length>0;return e.jsxs("div",{className:he("grid items-center px-4 py-3 group",D%2===0?"bg-black/[0.04] dark:bg-white/[0.04]":"",M&&!M.is_active&&"opacity-50"),style:{gridTemplateColumns:"24px 1fr 100px 28px 52px"},children:[e.jsx(Q,{className:"h-4 w-4 text-muted-foreground"}),e.jsxs("div",{className:"min-w-0 pr-4",children:[e.jsx("span",{className:"text-sm font-medium",children:h.name}),e.jsx("p",{className:"text-[11px] text-muted-foreground truncate",children:h.description})]}),e.jsx("span",{className:"text-[11px]",children:M?M.is_active?e.jsx("span",{className:"text-primary font-medium",children:"Active"}):e.jsx("span",{className:"text-muted-foreground",children:"Disabled"}):e.jsx("span",{className:"text-muted-foreground/50",children:"Not provisioned"})}),e.jsx("div",{children:M&&h.tier>0&&e.jsx(Ce,{checked:M.is_active,onCheckedChange:()=>m(M),className:"scale-75"})}),e.jsx("div",{className:"flex justify-end",children:M&&E&&e.jsx(N,{variant:"ghost",size:"icon",className:"h-7 w-7 opacity-0 group-hover:opacity-100",onClick:()=>I(M),title:"Configure settings",children:e.jsx(We,{className:"h-3.5 w-3.5"})})})]},p)}),e.jsx(Ee,{open:!!b,onOpenChange:p=>{p||I(null)},children:e.jsxs(Pe,{className:"w-[460px] sm:max-w-[460px] overflow-y-auto",children:[e.jsxs(ze,{children:[e.jsxs(Me,{children:[((y=jt[(b==null?void 0:b.agent_type)||""])==null?void 0:y.name)||"Agent"," settings"]}),e.jsx(rt,{children:(t=jt[(b==null?void 0:b.agent_type)||""])==null?void 0:t.description})]}),e.jsxs("div",{className:"space-y-6 py-6",children:[b&&e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx(W,{className:"text-sm",children:"Enabled"}),e.jsx(Ft,{text:"Whether this agent runs at all. Off â the agent processes no work of any kind, and its other settings here are ignored until you turn it back on. On â the agent is available and behaves according to the settings below. Turning an agent off is the hard stop; the settings below tune how it behaves while it's on."})]}),e.jsx(Ce,{checked:b.is_active,onCheckedChange:()=>m(b)})]}),b&&q(b.agent_type).map(({section:p,controls:D})=>e.jsxs("div",{className:"space-y-3 border-t pt-4",children:[e.jsx("p",{className:"text-xs font-semibold uppercase text-muted-foreground",children:p}),D.map(h=>{const M=h.spec.linkedBar?V.get(h.spec.linkedBar):void 0;return e.jsx(Ea,{control:h,linkedBar:M,saving:T===h.spec.key,onChange:Q=>S(b.agent_type,h.spec.key,Q),onChangeBar:M?Q=>S(b.agent_type,M.spec.key,Q):void 0},h.spec.key)})]},p)),b&&q(b.agent_type).length===0&&e.jsx("p",{className:"text-xs text-muted-foreground border-t pt-4",children:"This agent has no adjustable behavior settings yet â only the enable switch above."})]}),e.jsx(qe,{className:"border-t pt-4",children:e.jsx(N,{variant:"outline",onClick:()=>I(null),children:"Done"})})]})})]})})}function Va(s,l){return`${s===1?"One":"Many"}-to-${l===1?"One":"Many"}`}const Bt=s=>({id:null,key:"",label:"",description:"",from_repository_key:s,to_repository_key:"",cardinality:"many-to-one",direction:"directed",management_mode:"manual",enforce_acyclicity:!1});function Ut(s){switch(s){case"one-to-one":return{from_max:1,to_max:1};case"one-to-many":return{from_max:null,to_max:1};case"many-to-one":return{from_max:1,to_max:null};case"many-to-many":return{from_max:null,to_max:null};default:return{from_max:null,to_max:null}}}function Ka(s,l){return s===1&&l===1?"one-to-one":s===null&&l===1?"one-to-many":s===1&&l===null?"many-to-one":"many-to-many"}function Oa({repositoryKey:s}){var E,X;const{currentOrg:l}=Se(),_=l==null?void 0:l.id,i=Ge(),g=Xe(s),{repositories:f}=ts(),b=c.useMemo(()=>new Map(f.map(x=>[x.id,x])),[f]),[I,T]=c.useState(!1),[o,w]=c.useState(Bt(s)),[d,m]=c.useState(!1),[S,F]=c.useState(null),{data:P}=je({queryKey:["pim-edge-counts",_],enabled:!!_,queryFn:async()=>{const{data:x,error:r}=await U.rpc("pim_get_relationship_edge_counts",{p_org_id:_});return r?{}:x??{}},staleTime:60*1e3}),{data:V}=je({queryKey:["pim-auto-link-rules",_],enabled:!!_,queryFn:async()=>{const{data:x,error:r}=await U.rpc("pim_get_auto_link_rules",{p_org_id:_});return r?[]:x??[]},staleTime:60*1e3}),q=()=>{i.invalidateQueries({queryKey:["pim-schema"]}),i.invalidateQueries({queryKey:["pim-edge-counts"]}),i.invalidateQueries({queryKey:["pim-auto-link-rules"]})},y=c.useMemo(()=>[...g.relationshipTypes].sort((x,r)=>x.is_ownership!==r.is_ownership?x.is_ownership?-1:1:0),[g.relationshipTypes]),t=()=>{w(Bt(s)),T(!0)},p=x=>{const r=b.get(x.from_repository_id),j=b.get(x.to_repository_id);w({id:x.id,key:x.key,label:x.label||"",description:x.description??"",from_repository_key:(r==null?void 0:r.key)??"",to_repository_key:(j==null?void 0:j.key)??"",cardinality:Ka(x.from_max,x.to_max),direction:x.direction==="undirected"?"undirected":"directed",management_mode:x.management_mode||"manual",enforce_acyclicity:x.enforce_acyclicity??!1}),T(!0)},D=async()=>
26{if(!_)return;const x=o.key.trim().toLowerCase().replace(/\s+/g,"_");if(!x||!o.label.trim()||!o.to_repository_key){L.error("Label, key, and target entity type are required");return}m(!0);try{if(o.id){const{from_max:Z,to_max:A}=Ut(o.cardinality),{data:G,error:C}=await U.rpc("pim_update_relationship_type",{p_type_id:o.id,p_label:o.label.trim(),p_description:o.description.trim()||null,p_from_max:Z,p_to_max:A,p_direction:o.direction,p_enforce_acyclicity:o.enforce_acyclicity,p_management_mode:o.management_mode});if(C)throw C;const $=G;if(!($!=null&&$.success))throw new Error(($==null?void 0:$.error)||"update failed");q(),T(!1),L.success(`Relationship type "${o.label}" updated`),m(!1);return}const{from_max:r,to_max:j}=Ut(o.cardinality),n=f.find(Z=>Z.key===o.from_repository_key),R=f.find(Z=>Z.key===o.to_repository_key);if(!n||!R){L.error("Invalid repository selection"),m(!1);return}const{data:a,error:k}=await U.rpc("pim_create_relationship_type",{p_org_id:_,p_key:x,p_label:o.label.trim(),p_from_repository_id:n.id,p_to_repository_id:R.id,p_from_max:r,p_to_max:j,p_direction:o.direction,p_enforce_acyclicity:o.enforce_acyclicity,p_management_mode:o.management_mode,p_description:o.description.trim()||null});if(k)throw k;const Y=a;if(Y!=null&&Y.error)throw new Error(Y.error);q(),T(!1),L.success(`Relationship type "${o.label}" created`)}catch(r){const j=r instanceof Error?r.message:"Failed to create relationship type";L.error(j)}m(!1)},h=async()=>{if(S){try{const{error:x}=await U.rpc("pim_delete_relationship_type",{p_type_id:S.id});if(x)throw x;q(),L.success(`Deleted "${S.label}"`)}catch(x){const r=x instanceof Error?x.message:"Failed to delete";L.error(r)}F(null)}},M=x=>{var r;return((r=b.get(x))==null?void 0:r.label)??"Unknown"},Q=x=>(V??[]).filter(r=>r.relationship_type_id===x);return g.isLoading?e.jsx("div",{className:"py-8 text-center text-sm text-muted-foreground",children:"Loadingâ¦"}):e.jsxs("div",{className:"space-y-0",children:[e.jsxs("div",{className:"flex items-center justify-between px-4 py-2.5 border-b",children:[e.jsxs("span",{className:"text-xs text-muted-foreground",children:[y.length," relationship types involving ",((E=g.repository)==null?void 0:E.label)??s,".",(()=>{const x=Object.values(P??{}).reduce((r,j)=>r+j,0);return x>0?` ${x} edges total.`:""})()]}),e.jsxs(N,{size:"sm",className:"gap-1.5",onClick:t,children:[e.jsx(Ne,{className:"h-3.5 w-3.5"}),"New Relationship Type"]})]}),y.length===0&&e.jsxs("div",{className:"py-12 text-center",children:[e.jsx(qs,{className:"h-8 w-8 text-muted-foreground mx-auto mb-3"}),e.jsxs("p",{className:"text-sm text-muted-foreground mb-2",children:["No relationship types defined for ",((X=g.repository)==null?void 0:X.label)??s,"."]}),e.jsxs(N,{size:"sm",onClick:t,children:[e.jsx(Ne,{className:"h-3.5 w-3.5 mr-1.5"}),"Create First Relationship Type"]})]}),y.map((x,r)=>{const j=x.is_ownership,n=x.direction||"directed",R=(P==null?void 0:P[x.id])??0,a=Q(x.id);return e.jsxs("div",{className:"border-b last:border-b-0",children:[e.jsxs("div",{className:he("grid items-center px-4 py-2.5 group",r%2===0?"bg-black/[0.04] dark:bg-white/[0.04]":"",j&&"opacity-60"),style:{gridTemplateColumns:"20px 1fr 160px 100px 40px 52px"},children:[j?e.jsx(Es,{className:"h-3.5 w-3.5 text-muted-foreground/50"}):n==="undirected"?e.jsx(Sa,{className:"h-3.5 w-3.5 text-muted-foreground"}):e.jsx(vs,{className:"h-3.5 w-3.5 text-muted-foreground"}),e.jsx("span",{className:"text-sm font-medium truncate min-w-0 pr-2",children:x.label||x.key}),e.jsxs("span",{className:"text-[11px] text-muted-foreground",children:[M(x.from_repository_id)," ",n==="undirected"?"â":"â"," ",M(x.to_repository_id)]}),e.jsx("span",{className:"text-[11px] text-muted-foreground",children:Va(x.from_max,x.to_max)}),e.jsx("span",{className:"text-[11px] text-muted-foreground text-right",children:R>0?R:""}),e.jsx("div",{className:"flex justify-end gap-0.5",children:!j&&e.jsxs(e.Fragment,{children:[e.jsx(N,{variant:"ghost",size:"icon",className:"h-6 w-6 opacity-0 group-hover:opacity-100",onClick:()=>p(x),title:"Edit",children:e.jsx(We,{className:"h-3 w-3"})}),e.jsx(N,{variant:"ghost",size:"icon",className:"h-6 w-6 text-destructive opacity-0 group-hover:opacity-100",onClick:()=>F(x),title:"Delete",children:e.jsx($e,{className:"h-3 w-3"})})]})})]}),a.length>0&&e.jsx("div",{className:"px-4 pb-3",children:a.map(k=>e.jsxs("div",{className:"ml-[22px] px-3 py-2 bg-muted/40 rounded border-l-2 border-primary text-xs mb-1.5 last:mb-0",children:[e.jsxs("div",{className:"flex items-center gap-1.5 text-muted-foreground",children:[e.jsx(rs,{className:"h-3 w-3 text-primary"}),e.jsx("span",{className:"font-medium",children:"Auto-link rule"}),e.jsx("span",{children:"·"}),e.jsxs("span",{children:["Mode: ",e.jsx("strong",{children:k.target_mode})]}),k.target_source_attribute_key&&e.jsxs(e.Fragment,{children:[e.jsx("span",{children:"·"}),e.jsxs("span",{children:["Match ",e.jsx("strong",{children:k.target_source_attribute_key}),k.target_match_attribute_key&&e.jsxs(e.Fragment,{children:[" â ",e.jsx("strong",{children:k.target_match_attribute_key})]})]})]})]}),k.source_criteria&&Object.keys(k.source_criteria).length>0&&e.jsxs("div",{className:"text-muted-foreground mt-1",children:["Criteria: ",e.jsx("code",{className:"text-[10px] bg-muted px-1 py-0.5 rounded",children:JSON.stringify(k.source_criteria)})]}),k.edge_count>
260&&e.jsxs("div",{className:"text-primary font-medium mt-1",children:["⸠",k.edge_count," edges managed by this rule"]})]},k.id))})]},x.id)}),e.jsx(Ee,{open:I,onOpenChange:T,children:e.jsxs(Pe,{className:"w-[500px] sm:max-w-[500px] overflow-y-auto",children:[e.jsxs(ze,{children:[e.jsx(Me,{children:o.id?"Edit Relationship Type":"New Relationship Type"}),e.jsx(rt,{children:"Define how two entity types relate to each other."})]}),e.jsxs("div",{className:"space-y-4 py-4",children:[e.jsxs("div",{className:"space-y-1",children:[e.jsx(W,{className:"text-xs font-semibold uppercase text-muted-foreground",children:"Label"}),e.jsx(te,{value:o.label,onChange:x=>{const r=x.target.value;w(j=>({...j,label:r,...j.id?{}:{key:r.trim().toLowerCase().replace(/\s+/g,"_").replace(/[^a-z0-9_]/g,"")}}))},placeholder:"e.g. Product Brand, Cross-Sell"})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx(W,{className:"text-xs font-semibold uppercase text-muted-foreground",children:"Key"}),e.jsx(te,{value:o.key,disabled:!!o.id,onChange:x=>w(r=>({...r,key:x.target.value})),placeholder:"product_brand",className:"font-mono text-sm"}),!o.id&&e.jsx("p",{className:"text-[10px] text-muted-foreground",children:"Auto-generated from label. Cannot change after creation."})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx(W,{className:"text-xs font-semibold uppercase text-muted-foreground",children:"Description"}),e.jsx(te,{value:o.description,onChange:x=>w(r=>({...r,description:x.target.value})),placeholder:"What does this relationship represent?"})]}),e.jsx("div",{className:"border-t pt-4"}),e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsxs("div",{className:"space-y-1",children:[e.jsx(W,{className:"text-xs font-semibold uppercase text-muted-foreground",children:"From (source)"}),e.jsxs(re,{value:o.from_repository_key,onValueChange:x=>w(r=>({...r,from_repository_key:x})),children:[e.jsx(ie,{children:e.jsx(ne,{placeholder:"Select..."})}),e.jsx(le,{children:f.map(x=>e.jsx(J,{value:x.key,children:x.label},x.key))})]})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx(W,{className:"text-xs font-semibold uppercase text-muted-foreground",children:"To (target)"}),e.jsxs(re,{value:o.to_repository_key,onValueChange:x=>w(r=>({...r,to_repository_key:x})),children:[e.jsx(ie,{children:e.jsx(ne,{placeholder:"Select..."})}),e.jsx(le,{children:f.map(x=>e.jsx(J,{value:x.key,children:x.label},x.key))})]})]})]}),e.jsx("div",{className:"border-t pt-4"}),e.jsxs("div",{className:"space-y-1",children:[e.jsx(W,{className:"text-xs font-semibold uppercase text-muted-foreground",children:"Cardinality"}),e.jsxs(re,{value:o.cardinality,onValueChange:x=>w(r=>({...r,cardinality:x})),children:[e.jsx(ie,{children:e.jsx(ne,{})}),e.jsxs(le,{children:[e.jsx(J,{value:"one-to-one",children:"One-to-One"}),e.jsx(J,{value:"one-to-many",children:"One-to-Many"}),e.jsx(J,{value:"many-to-one",children:"Many-to-One"}),e.jsx(J,{value:"many-to-many",children:"Many-to-Many"})]})]}),e.jsxs("p",{className:"text-[10px] text-muted-foreground",children:[o.cardinality==="one-to-one"&&"Each source links to exactly one target, and vice versa.",o.cardinality==="one-to-many"&&"Each target belongs to one source, but a source can have many targets.",o.cardinality==="many-to-one"&&"Each source links to one target, but a target can be linked from many sources.",o.cardinality==="many-to-many"&&"No limits â any source can link to any number of targets and vice versa."]})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx(W,{className:"text-xs font-semibold uppercase text-muted-foreground",children:"Direction"}),e.jsxs(re,{value:o.direction,onValueChange:x=>w(r=>({...r,direction:x})),children:[e.jsx(ie,{children:e.jsx(ne,{})}),e.jsxs(le,{children:[e.jsx(J,{value:"directed",children:"Directed (A â B)"}),e.jsx(J,{value:"undirected",children:"Bidirectional (A â B)"})]})]}),e.jsx("p",{className:"text-[10px] text-muted-foreground",children:o.direction==="directed"?"The relationship has a direction: source points to target.":"The relationship works both ways â if A links to B, B also links to A."})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx(W,{className:"text-xs font-semibold uppercase text-muted-foreground",children:"Management"}),e.jsxs(re,{value:o.management_mode,onValueChange:x=>w(r=>({...r,management_mode:x})),children:[e.jsx(ie,{children:e.jsx(ne,{})}),e.jsxs(le,{children:[e.jsx(J,{value:"manual",children:"Manual"}),e.jsx(J,{value:"rule",children:"Rule-managed"}),e.jsx(J,{value:"both",children:"Manual + Rule"})]})]}),e.jsxs("p",{className:"text-[10px] text-muted-foreground",children:[o.management_mode==="manual"&&"Edges created and removed by users or agents manually.",o.management_mode==="rule"&&"Edges managed entirely by auto-link rules. Manual linking is blocked.",o.management_mode==="both"&&"Auto-link rules manage edges, but manual overrides are also allowed."]})]}),e.jsx("div",{className:"border-t pt-4"}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx("span",{className:"text-sm",children:"Enforce acyclicity"}),e.jsx("p",{className:"text-[10px] text-muted-foreground",children:"Prevents circular references (A â B â C â A). Required for tree structures."})]}),e.jsx(Ce,{checked:o.enforce_acyclicity,onCheckedChange:x=>w(r=>({...r,enforce_acyclicity:x}))})]})]}),e.jsxs(qe,{className:"border-t pt-4",children:[e.jsx(N,{variant:"outline",onClick:()=>T(!1),children:"Cancel"}),e.jsx(N,{onClick:D,disabled:d||!o.key.trim()||!o.label.trim()||!o.to_repository_key,children:d?"Savingâ¦":o.id?"Save":"Create"})]})]})}),e.jsx(it,{open:!!S,onOpenChange:x=>{x||F(null)},children:e.jsxs(nt,{children:[e.jsxs(lt,{children:[e.jsxs(ot,{className:"flex items-center gap-2",children:[e.jsx(xt,{className:"h-5 w-5 text-destructive"}),"Delete â",S==null?void 0:S.label,"â?"]}
26),e.jsxs(ct,{children:["This permanently deletes the relationship type and all ",(P==null?void 0:P[(S==null?void 0:S.id)??""])??0," edges. Records are not deleted, but their links through this type will be lost. This cannot be undone."]})]}),e.jsxs(dt,{children:[e.jsx(ut,{children:"Cancel"}),e.jsx(pt,{className:"bg-destructive hover:bg-destructive/90",onClick:h,children:"Delete Permanently"})]})]})})]})}function $a(){const{currentOrg:s}=Se(),l=s==null?void 0:s.id,_=Ge(),[i,g]=c.useState(null),[f,b]=c.useState(!1),{data:I=[],isLoading:T}=je({queryKey:["soft-deleted-records",l],queryFn:async()=>{const{data:m,error:S}=await U.rpc("list_soft_deleted_records",{p_org_id:l});if(S)throw S;return m??[]},enabled:!!l}),o=ht({mutationFn:async m=>{const{data:S,error:F}=await U.rpc("undelete_record",{p_record_id:m.id,p_restore_orphans:m.orphans});if(F)throw F;return S},onSuccess:()=>{L.success("Record restored"),_.invalidateQueries({queryKey:["soft-deleted-records",l]}),g(null),b(!1)},onError:m=>L.error(`Restore failed: ${m.message}`)}),w=ht({mutationFn:async m=>{const{data:S,error:F}=await U.rpc("hard_delete_record",{p_record_id:m.id,p_confirm:!0,p_cascade_orphans:m.orphans});if(F)throw F;return S},onSuccess:()=>
26{L.success("Record permanently deleted"),_.invalidateQueries({queryKey:["soft-deleted-records",l]}),g(null),b(!1)},onError:m=>L.error(`Delete failed: ${m.message}`)}),d=o.isPending||w.isPending;return e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{children:[e.jsx("h2",{className:"text-sm font-semibold text-foreground",children:"Soft-Deleted Records"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Records here are deleted but recoverable. Restore them, or delete them permanently â permanent deletion cannot be undone. Only records that were soft-deleted appear here."})]}),T?e.jsxs("div",{className:"flex items-center gap-2 text-sm text-muted-foreground py-8 justify-center",children:[e.jsx(Ze,{className:"h-4 w-4 animate-spin"})," Loading deleted recordsâ¦"]}):I.length===0?e.jsx(me,{className:"border-dashed border-border/60 bg-transparent p-8 text-center",children:e.jsx("p",{className:"text-sm text-muted-foreground",children:"Nothing here. Deleted records will appear in this list until you restore or permanently delete them."})}):e.jsx(me,{className:"border-border/50 bg-card/50 overflow-hidden",children:e.jsx("div",{className:"divide-y divide-border/50",children:I.map(m=>e.jsxs("div",{className:"flex items-center justify-between gap-3 px-4 py-3",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"text-sm font-medium text-foreground truncate",children:m.title}),e.jsx(se,{variant:"outline",className:"text-[10px] px-1.5 py-0 capitalize",children:m.repo_key}),m.related_count>0&&e.jsxs(se,{variant:"secondary",className:"text-[10px] px-1.5 py-0",children:[m.related_count," related"]})]}),e.jsxs("p",{className:"text-xs text-muted-foreground mt-0.5",children:["Deleted ",new Date(m.deleted_at).toLocaleString(),m.deleted_by_email?` by ${m.deleted_by_email}`:""]})]}),e.jsxs("div",{className:"flex items-center gap-1.5 shrink-0",children:[e.jsxs(N,{variant:"outline",size:"sm",className:"gap-1.5",disabled:d,onClick:()=>{b(m.related_count>0),g({kind:"restore",rec:m})},children:[e.jsx(is,{className:"h-3.5 w-3.5"})," Restore"]}),e.jsxs(N,{variant:"ghost",size:"sm",className:"gap-1.5 text-destructive hover:text-destructive",disabled:d,onClick:()=>{b(m.related_count>0),g({kind:"hard_delete",rec:m})},children:[e.jsx($e,{className:"h-3.5 w-3.5"})," Delete permanently"]})]})]},m.record_id))})}),e.jsx(it,{open:!!i,onOpenChange:m=>{m||(g(null),b(!1))},children:e.jsxs(nt,{children:[e.jsxs(lt,{children:[e.jsxs(ot,{className:"flex items-center gap-2",children:[(i==null?void 0:i.kind)==="hard_delete"&&e.jsx(xt,{className:"h-4 w-4 text-destructive"}),(i==null?void 0:i.kind)==="restore"?"Restore this record?":"Permanently delete this record?"]}),e.jsx(ct,{asChild:!0,children:e.jsxs("div",{className:"space-y-3",children:[e.jsx("p",{children:(i==null?void 0:i.kind)==="restore"?`"${i==null?void 0:i.rec.title}" will be restored to your catalog.`:`"${i==null?void 0:i.rec.title}" will be permanently removed. This cannot be undone.`}),i&&i.rec.related_count>0&&e.jsxs("label",{className:"flex items-start gap-2 text-sm rounded-md border border-border/60 p-3 cursor-pointer",children:[e.jsx("input",{type:"checkbox",checked:f,onChange:m=>b(m.target.checked),className:"mt-0.5"}),e.jsx("span",{children:i.kind==="restore"?`Also restore the ${i.rec.related_count} related item(s) that were deleted with it.`:`Also permanently delete the ${i.rec.related_count} related item(s) (orphaned variants and their media). Shared items are never affected.`})]})]})})]}),e.jsxs(dt,{children:[e.jsx(ut,{disabled:d,children:"Cancel"}),e.jsxs(pt,{className:(i==null?void 0:i.kind)==="hard_delete"?"bg-destructive text-destructive-foreground hover:bg-destructive/90":"",disabled:d,onClick:m=>{if(m.preventDefault(),!i)return;const S={id:i.rec.record_id,orphans:f};i.kind==="restore"?o.mutate(S):w.mutate(S)},children:[d&&e.jsx(Ze,{className:"h-4 w-4 animate-spin mr-1.5"}),(i==null?void 0:i.kind)==="restore"?"Restore":"Delete permanently"]})]})]})})]})}const Ye="__default__";function Ga({open:s,onOpenChange:l,orgId:_,repoKey:i,repoLabel:g,currentDisplayNameAttributeId:f}){const{attributes:b}=Xe(i),I=Ge(),[T,o]=c.useState(!1),[w,d]=c.useState(f??Ye);c.useEffect(()=>{s&&d(f??Ye)},[s,f,i]);const m=w!==(f??Ye),S=async()=>{o(!0);try{const F=w===Ye?null:w,{error:P}=await U.rpc("pim_set_entity_display_name",{p_org_id:_,p_repository_key:i,p_attribute_id:F});if(P)throw P;await I.invalidateQueries({queryKey:["pim-repositories",_]}),L.success("Display name updated"),l(!1)}catch(F){L.error(F instanceof Error?F.message:"Failed to save")}finally{o(!1)}};return e.jsx(Ee,{open:s,onOpenChange:l,children:e.jsxs(Pe,{side:"right",className:"w-[400px] sm:max-w-[400px] flex flex-col",children:[e.jsxs(ze,{children:[e.jsxs(Me,{children:[g," settings"]}),e.jsx(rt,{children:"Entity-level configuration"})]}),e.jsx("div",{className:"flex-1 overflow-y-auto py-4 space-y-8",children:e.jsxs("section",{className:"space-y-2",children:[e.jsx("h3",{className:"text-xs font-semibold uppercase tracking-wider text-muted-foreground",children:"Display name"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"The attribute shown as this entity's name across the app â in grids, detail headers, relationships, and CC."}),e.jsxs(re,{value:w,onValueChange:d,children:[e.jsx(ie,{className:"w-full",children:e.jsx(ne,{})}),e.jsxs(le,{children:[e.jsx(J,{value:Ye,children:"Default (identity attribute)"}),[...b].sort((F,P)=>F.display_order-P.display_order).map(F=>e.jsx(J,{value:F.id,children:F.label}
26,F.id))]})]}),w!==Ye&&e.jsx("button",{type:"button",className:"text-xs text-primary hover:underline",onClick:()=>d(Ye),children:"Reset to default"})]})}),e.jsxs("div",{className:"border-t pt-4 flex items-center justify-end gap-2",children:[e.jsx(N,{variant:"outline",onClick:()=>l(!1),disabled:T,children:"Cancel"}),e.jsx(N,{onClick:S,disabled:!m||T,children:T?"Savingâ¦":"Save"})]})]})})}const Ba=[{v:"text",l:"Text"},{v:"richtext",l:"Rich Text"},{v:"number",l:"Number"},{v:"bool",l:"Boolean"},{v:"date",l:"Date"},{v:"list",l:"List"},{v:"json",l:"JSON"},{v:"array",l:"Array"},{v:"table",l:"Table"}];function us({node:s,depth:l,selectedId:_,onSelect:i,expanded:g,toggle:f,onAddChild:b,onRename:I,onDelete:T,onDrop:o}){const w=s.children.length>0,d=g[s.id],m=_===s.id,S=c.useRef(null),[F,P]=c.useState("none"),V=p=>{p.dataTransfer.setData("text/plain",s.id),p.dataTransfer.effectAllowed="move"},q=p=>{var h;p.preventDefault(),p.dataTransfer.dropEffect="move";const D=(h=S.current)==null?void 0:h.getBoundingClientRect();if(D){const M=p.clientY-D.top;P(M<D.height*.3?"above":"child")}},y=()=>P("none"),t=p=>{p.preventDefault();const D=p.dataTransfer.getData("text/plain");if(D===s.id){P("none");return}F==="child"?o(D,s.id):F==="above"&&o(D,s.parent_record_id),P("none")};return e.jsxs(e.Fragment,{children:[e.jsxs("div",{ref:S,draggable:!0,onDragStart:V,onDragOver:q,onDragLeave:y,onDrop:t,className:he("flex items-center gap-1 px-2 py-1.5 cursor-pointer rounded-md group text-sm hover:bg-muted/50",m&&"bg-primary/10 text-primary font-medium",F==="above"&&"border-t-2 border-primary",F==="child"&&"bg-primary/10 ring-1 ring-primary ring-dashed"),style:{paddingLeft:`${l*16+8}px`},onClick:()=>i(s.id),children:[e.jsx(wt,{className:"h-3 w-3 text-muted-foreground/40 cursor-grab shrink-0"}),w?e.jsx("button",{className:"p-0.5 shrink-0",onClick:p=>{p.stopPropagation(),f(s.id)},children:d?e.jsx(Jt,{className:"h-3.5 w-3.5 text-muted-foreground"}):e.jsx(Tt,{className:"h-3.5 w-3.5 text-muted-foreground"})}):e.jsx("span",{className:"w-[18px] shrink-0"}),d&&w?e.jsx(Ps,{className:"h-3.5 w-3.5 text-muted-foreground shrink-0"}):e.jsx(zs,{className:"h-3.5 w-3.5 text-muted-foreground shrink-0"}),e.jsx("span",{className:"truncate flex-1",children:s.name||"(unnamed)"}),e.jsxs("div",{className:"flex items-center gap-0.5 opacity-0 group-hover:opacity-100 shrink-0",children:[e.jsx(N,{variant:"ghost",size:"icon",className:"h-5 w-5",onClick:p=>{p.stopPropagation(),I(s)},children:e.jsx(We,{className:"h-2.5 w-2.5"})}),e.jsx(N,{variant:"ghost",size:"icon",className:"h-5 w-5",onClick:p=>{p.stopPropagation(),b(s.id)},children:e.jsx(Ne,{className:"h-2.5 w-2.5"})}),e.jsx(N,{variant:"ghost",size:"icon",className:"h-5 w-5",onClick:p=>{p.stopPropagation(),T(s)},children:e.jsx($e,{className:"h-2.5 w-2.5 text-muted-foreground hover:text-destructive"})})]})]}),w&&d&&s.children.map(p=>e.jsx(us,{node:p,depth:l+1,selectedId:_,onSelect:i,expanded:g,toggle:f,onAddChild:b,onRename:I,onDelete:T,onDrop:o}
26,p.id))]})}function Ua(){const{currentOrg:s}=Se(),l=s==null?void 0:s.id,{collidingIds:_}=cs(l),i=Ge(),g=Xe("product"),f=Xe("variant"),{data:b}=je({queryKey:["pim-lists",l],enabled:!!l,queryFn:async()=>{const{data:v,error:K}=await U.rpc("pim_get_lists",{p_org_id:l});if(K)throw K;return v??[]}}),{data:I}=je({queryKey:["pim-categories",l],enabled:!!l,queryFn:async()=>{const{data:v,error:K}=await U.rpc("pim_get_categories",{p_org_id:l});if(K)throw K;return(v??[]).map(ae=>({id:ae.id,parent_record_id:ae.parent_record_id,name:ae.name,full_path:ae.full_path}))}}),[T,o]=c.useState(null),[w,d]=c.useState({}),[m,S]=c.useState({open:!1,mode:"add",parentId:null,editNode:null}),[F,P]=c.useState(""),[V,q]=c.useState(null),[y,t]=c.useState({open:!1,level:"product",mode:"create"}),[p,D]=c.useState({key:"",label:"",data_type:"text",list_id:null}),[h,M]=c.useState("__none"),[Q,E]=c.useState(!1),[X,x]=c.useState(null),[r,j]=c.useState("product"),{data:n}=je({queryKey:["pim-cat-attrs",T],enabled:!!T,queryFn:async()=>{const{data:v,error:K}=await U.rpc("pim_get_category_attributes",{p_category_record_id:T});if(K)throw K;return v??[]}}),R=c.useMemo(()=>{const v=new Map((I??[]).map(oe=>[oe.id,{...oe,children:[]}])),K=[];for(const oe of v.values())oe.parent_record_id&&v.has(oe.parent_record_id)?v.get(oe.parent_record_id).children.push(oe):K.push(oe);const ae=oe=>{oe.sort((pe,De)=>(pe.name||"").localeCompare(De.name||"")),oe.forEach(pe=>ae(pe.children))};return ae(K),K},[I]),a=c.useMemo(()=>({product:g.attributes.filter(v=>v.category_scoped),variant:f.attributes.filter(v=>v.category_scoped)}),[g.attributes,f.attributes]),k=c.useMemo(()=>new Set(n??[]),[n]),Y=c.useMemo(()=>(I??[]).find(v=>v.id===T),[I,T]),Z=c.useCallback(()=>i.invalidateQueries({queryKey:["pim-categories"]}),[i]),A=()=>{i.invalidateQueries({queryKey:["pim-cat-attrs"]}),i.invalidateQueries({queryKey:["pim-schema"]})},G=v=>{S({open:!0,mode:"add",parentId:v,editNode:null}),P("")},C=v=>{S({open:!0,mode:"rename",parentId:null,editNode:v}),P(v.name||"")},$=async()=>{const v=F.trim();if(!(!v||!l))if(m.mode==="rename"&&m.editNode){const{data:K,error:ae}=await U.rpc("pim_rename_category",{p_record_id:m.editNode.id,p_name:v});if(ae||!(K!=null&&K.success)){L.error("Failed to rename");return}Z(),S(oe=>({...oe,open:!1})),L.success("Renamed")}else{const{data:K,error:ae}=await U.rpc("pim_create_category",{p_org_id:l,p_name:v,p_parent_record_id:m.parentId??null});if(ae||!(K!=null&&K.success)){L.error("Failed to create category");return}m.parentId&&d(oe=>({...oe,[m.parentId]:!0})),Z(),S(oe=>({...oe,open:!1})),L.success(`Category "${v}" created`)}},ye=async()=>{if(!V)return;const{data:v,error:K}=await U.rpc("pim_delete_category",{p_record_id:V.id});if(K||!(v!=null&&v.success)){L.error("Failed to delete");return}T===V.id&&o(null),Z(),q(null),L.success("Deleted")},ce=c.useCallback(async(v,K)=>{if(!v)return;const ae=(De,u)=>{if(!De)return!1;if(De===u)return!0;const H=(I??[]).find(B=>B.id===De);return H?ae(H.parent_record_id,u):!1};if(K&&ae(K,v)){L.error("Cannot move a category into its own descendant");return}const{data:oe,error:pe}=await U.rpc("pim_reparent_category",{p_record_id:v,p_new_parent:K});if(pe){L.error("Failed to move category");return}K&&d(De=>({...De,[K]:!0})),Z(),L.success("Category moved")},[I,Z]),Ae=async v=>{if(!T)return;const{error:K}=await U.rpc("pim_set_category_attributes",{p_category_record_id:T,p_attribute_ids:v});if(K){L.error("Failed to update assignment");return}A()},O=async()=>{if(!l||!T)return;const v=p.key.trim().toLowerCase().replace(/\s+/g,"_");if(!v){L.error("Attribute name required");return}if(p.data_type==="list"&&!p.list_id){L.error("Pick a list");return}const{data:K,error:ae}=await U.rpc("pim_upsert_attribute",{p_org_id:l,p_repository_key:y.level,p_key:v,p_label:p.label||null,p_data_type:p.data_type,p_field_group_id:null,p_list_id:p.data_type==="list"?p.list_id:null,p_category_scoped:!0});if(ae||!(K!=null&&K.success)){L.error("Failed to create attribute");return}await Ae([...n??[],K.attribute_id]),t(oe=>({...oe,open:!1})),D({key:"",label:"",data_type:"text",list_id:null}),L.success(`Created & assigned "${v}"`)},ue=async()=>{h!=="__none"&&(await Ae([...n??[],h]),t(v=>({...v,open:!1})),M("__none"),L.success("Assigned"))},xe=async v=>Ae((n??[]).filter(K=>
26K!==v)),Ve=(v,K)=>{x(v),j(K),E(!0)},Je=v=>{const K=a[v],ae=K.filter(pe=>k.has(pe.id)),oe=K.filter(pe=>!k.has(pe.id));return e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("span",{className:"text-xs font-medium text-muted-foreground capitalize",children:[v,"-level"]}),e.jsxs("div",{className:"flex gap-1",children:[e.jsxs(N,{variant:"outline",size:"sm",className:"h-7 text-xs gap-1",onClick:()=>{D({key:"",label:"",data_type:"text",list_id:null}),t({open:!0,level:v,mode:"create"})},children:[e.jsx(Ne,{className:"h-3 w-3"})," New"]}),e.jsx(N,{variant:"outline",size:"sm",className:"h-7 text-xs",disabled:oe.length===0,onClick:()=>{M("__none"),t({open:!0,level:v,mode:"assign"})},children:"Assign existing"})]})]}),ae.length===0?e.jsxs("p",{className:"text-xs text-muted-foreground",children:["No category-scoped ",v," attributes assigned."]}):e.jsx("div",{children:ae.map((pe,De)=>e.jsxs("div",{className:he("grid items-center px-2 py-2 hover:bg-accent/50 group",De%2===0?"bg-black/[0.04] dark:bg-white/[0.04]":""),style:{gridTemplateColumns:"1fr 56px 52px"},children:[e.jsxs("span",{className:"text-sm font-medium truncate flex items-center gap-1.5",children:[e.jsx("span",{className:"truncate",children:pe.label||pe.key}),_.has(pe.id)&&e.jsx("span",{title:`"${pe.label}" also exists as a global attribute. Review which you intend â this is informational only.`,className:"shrink-0 text-[10px] leading-none px-1.5 py-0.5 rounded border border-amber-400/60 text-amber-600 dark:text-amber-400",children:"also global"})]}),e.jsx("span",{className:"text-[11px] text-muted-foreground",children:pe.data_type}),e.jsxs("div",{className:"flex justify-end gap-0.5 opacity-0 group-hover:opacity-100",children:[e.jsx(N,{variant:"ghost",size:"icon",className:"h-6 w-6",onClick:()=>Ve(pe,v),title:"Edit",children:e.jsx(We,{className:"h-3 w-3"})}),e.jsx(N,{variant:"ghost",size:"icon",className:"h-6 w-6 text-destructive",onClick:()=>xe(pe.id),title:"Remove from category",children:e.jsx(kt,{className:"h-3 w-3"})})]})]},pe.id))})]})},bt=(a[y.level]||[]).filter(v=>!k.has(v.id)),[et,Le]=c.useState(!1);return e.jsxs("div",{className:"flex gap-4 h-[calc(100vh-16rem)]",children:[e.jsxs(me,{className:"w-[30%] flex-shrink-0 flex flex-col",children:[e.jsxs(Be,{className:"py-3 flex flex-row items-center justify-between",children:[e.jsx(Ue,{className:"text-sm",children:"Categories"}),e.jsxs(N,{size:"sm",variant:"outline",className:"h-7 text-xs gap-1",onClick:()=>G(null),children:[e.jsx(Ne,{className:"h-3 w-3"})," Add"]})]}),e.jsxs(Te,{className:"flex-1 overflow-auto pt-0",children:[R.length===0?e.jsx("p",{className:"text-xs text-muted-foreground py-2",children:"No categories yet."}):R.map(v=>e.jsx(us,{node:v,depth:0,selectedId:T,onSelect:o,expanded:w,toggle:K=>d(ae=>({...ae,[K]:!ae[K]})),onAddChild:K=>G(K),onRename:C,onDelete:q,onDrop:ce},v.id)),e.jsx("div",{className:he("mt-2 py-2 border border-dashed rounded text-center text-xs text-muted-foreground",et&&"border-primary bg-primary/5"),onDragOver:v=>{v.preventDefault(),Le(!0)},onDragLeave:()=>Le(!1),onDrop:v=>{v.preventDefault();const K=v.dataTransfer.getData("text/plain");K&&ce(K,null),Le(!1)},children:"Drop here to make root-level"})]})]}),e.jsx(me,{className:"flex-1 flex flex-col",children:Y?e.jsxs(e.Fragment,{children:[e.jsxs(Be,{className:"py-3 border-b",children:[e.jsx(Ue,{className:"text-sm",children:Y.full_path||Y.name}),e.jsx("p",{className:"text-xs text-muted-foreground mt-0.5",children:"Category-scoped attributes appear only on products in this category."})]}),e.jsxs(Te,{className:"flex-1 overflow-auto p-4 space-y-6",children:[Je("product"),Je("variant")]})]}):e.jsx("div",{className:"flex-1 flex items-center justify-center text-sm text-muted-foreground",children:"Select a category to manage its attributes."})}),e.jsx(Ee,{open:m.open,onOpenChange:v=>{v||S(K=>({...K,open:!1}))},children:e.jsxs(Pe,{className:"w-[400px] sm:max-w-[400px]",children:[e.jsxs(ze,{children:[e.jsx(Me,{children:m.mode==="rename"?"Rename Category":m.parentId?"Add Child Category":"Add Category"}),m.mode==="add"&&m.parentId&&e.jsx(rt,{children:"Creates a child under the selected category."})]}),e.jsx("div",{className:"space-y-4 py-4",children:e.jsxs("div",{className:"space-y-1",children:[e.jsx(W,{className:"text-xs font-semibold uppercase text-muted-foreground",children:"Name"}),e.jsx(te,{value:F,onChange:v=>P(v.target.value),placeholder:"e.g. Jackets, Snowboards, Helmets",autoF
26ocus:!0,onKeyDown:v=>{v.key==="Enter"&&(v.preventDefault(),$())}})]})}),e.jsxs(qe,{className:"border-t pt-4",children:[e.jsx(N,{variant:"outline",onClick:()=>S(v=>({...v,open:!1})),children:"Cancel"}),e.jsx(N,{onClick:$,disabled:!F.trim(),children:m.mode==="rename"?"Save":"Create"})]})]})}),e.jsx(it,{open:!!V,onOpenChange:v=>{v||q(null)},children:e.jsxs(nt,{children:[e.jsxs(lt,{children:[e.jsxs(ot,{children:["Delete â",V==null?void 0:V.name,"â?"]}),e.jsx(ct,{children:V!=null&&V.children.length?`Its ${V.children.length} child categor${V.children.length===1?"y":"ies"} will move up to the parent.`:"Products in this category will become uncategorized."})]}),e.jsxs(dt,{children:[e.jsx(ut,{children:"Cancel"}),e.jsx(pt,{onClick:ye,className:"bg-destructive hover:bg-destructive/90",children:"Delete"})]})]})}),e.jsx(Ee,{open:y.open,onOpenChange:v=>{v||t(K=>({...K,open:!1}))},children:e.jsxs(Pe,{className:"w-[500px] sm:max-w-[500px] overflow-y-auto",children:[e.jsxs(ze,{children:[e.jsxs(Me,{children:[y.mode==="create"?"New":"Assign"," ",y.level,"-level attribute"]}),e.jsx(rt,{children:y.mode==="create"?`Creates a category-scoped attribute and assigns it to "${Y==null?void 0:Y.name}".`:`Add an existing category-scoped attribute to "${Y==null?void 0:Y.name}".`})]}),y.mode==="create"?e.jsxs("div",{className:"space-y-4 py-4",children:[e.jsxs("div",{className:"space-y-1",children:[e.jsx(W,{className:"text-xs font-semibold uppercase text-muted-foreground",children:"Attribute Name"}),e.jsx(te,{value:p.key,onChange:v=>D(K=>({...K,key:v.target.value})),placeholder:"e.g. flex_rating",className:"font-mono text-sm"})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx(W,{className:"text-xs font-semibold uppercase text-muted-foreground",children:"Display Label"}),e.jsx(te,{value:p.label,onChange:v=>D(K=>({...K,label:v.target.value})),placeholder:"e.g. Flex Rating"})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx(W,{className:"text-xs font-semibold uppercase text-muted-foreground",children:"Data Type"}),e.jsxs(re,{value:p.data_type,onValueChange:v=>D(K=>({...K,data_type:v,list_id:v==="list"?K.list_id:null})),children:[e.jsx(ie,{children:e.jsx(ne,{})}),e.jsx(le,{children:Ba.map(v=>e.jsx(J,{value:v.v,children:v.l},v.v))})]})]}),p.data_type==="list"&&e.jsxs("div",{className:"space-y-1",children:[e.jsx(W,{className:"text-xs font-semibold uppercase text-muted-foreground",children:"List"}),e.jsxs(re,{value:p.list_id||"__none",onValueChange:v=>D(K=>({...K,list_id:v==="__none"?null:v})),children:[e.jsx(ie,{children:e.jsx(ne,{placeholder:"â Select â"})}),e.jsxs(le,{children:[e.jsx(J,{value:"__none",children:"â Select â"}),(b??[]).map(v=>e.jsx(J,{value:v.id,children:v.name},v.id))]})]})]}),e.jsxs(qe,{className:"border-t pt-4",children:[e.jsx(N,{variant:"outline",onClick:()=>t(v=>({...v,open:!1})),children:"Cancel"}),e.jsx(N,{onClick:O,disabled:!p.key.trim(),children:"Create & Assign"})]})]}):e.jsxs("div",{className:"space-y-4 py-4",children:[e.jsxs("div",{className:"space-y-1",children:[e.jsx(W,{className:"text-xs font-semibold uppercase text-muted-foreground",children:"Select Attribute"}),e.jsxs(re,{value:h,onValueChange:M,children:[e.jsx(ie,{children:e.jsx(ne,{placeholder:"Pick an attributeâ¦"})}),e.jsxs(le,{children:[e.jsx(J,{value:"__none",children:"â Select â"}),bt.map(v=>e.jsxs(J,{value:v.id,children:[v.label||v.key," (",v.data_type,")"]},v.id))]})]})]}),e.jsxs(qe,{className:"border-t pt-4",children:[e.jsx(N,{variant:"outline",onClick:()=>t(v=>({...v,open:!1})),children:"Cancel"}),e.jsx(N,{onClick:ue,disabled:h==="__none",children:"Assign"})]})]})]})}),e.jsx(ds,{open:Q,onOpenChange:E,attribute:X,orgId:l,repositoryKey:r,lists:b,fieldGroups:(r==="variant"?f:g).fieldGroups,defaultCategoryScoped:!0,onSaved:A})]})}function Qa(s,l){const _=String(s??"").toLowerCase(),i=l.value.toLowerCase();switch(l.operator){case"equals":return _===i;case"not_equals":return _!==i;case"contains":return _.includes(i);case"not_contains":return!_.includes(i);case"begins_with":return _.startsWith(i);default:return!0}}function ps({items:s}){const[l,_]=c.useState(null),[i,g]=c.useState({}),f=c.useCallback(d=>{_(m=>!m||m.key!==d?{key:d,direction:"ASC"}:m.direction==="ASC"?{key:d,direction:"DESC"}:null)},[]),b=c.useCallback(d=>!l||l.key!==d?null:l.direction,[l]),I=c.useCallback((d,m)=>{g(S=>{const F={...S};
26return m?F[d]=m:delete F[d],F})},[]),T=c.useCallback(d=>i[d],[i]),o=c.useCallback(()=>{g({}),_(null)},[]);return{processedItems:c.useMemo(()=>{let d=[...s];const m=Object.values(i);if(m.length>0&&(d=d.filter(S=>m.every(F=>Qa(S[F.columnKey],F)))),l){const{key:S,direction:F}=l;d.sort((P,V)=>{const q=P[S],y=V[S];if(q==null&&y==null)return 0;if(q==null)return 1;if(y==null)return-1;if(typeof q=="number"&&typeof y=="number")return F==="ASC"?q-y:y-q;if(typeof q=="boolean"&&typeof y=="boolean")return F==="ASC"?q===y?0:q?-1:1:q===y?0:q?1:-1;const t=String(q).toLowerCase(),p=String(y).toLowerCase(),D=t.localeCompare(p);return F==="ASC"?D:-D})}return d},[s,i,l]),sortState:l,columnFilters:i,handleSort:f,getSortDirection:b,setColumnFilter:I,getColumnFilter:T,clearAllFilters:o}}const Ha=[{value:"equals",label:"Equals"},{value:"not_equals",label:"Does Not Equal"},{value:"contains",label:"Contains"},{value:"not_contains",label:"Does Not Contain"},{value:"begins_with",label:"Begins With"}],ke=({columnKey:s,label:l,sortDirection:_,onSort:i,filter:g,onFilterChange:f,className:b,sortable:I=!0,filterable:T=!0})=>{const[o,w]=c.useState(!1),[d,m]=c.useState((g==null?void 0:g.operator)||"contains"),[S,F]=c.useState((g==null?void 0:g.value)||""),P=()=>{S.trim()?f(s,{columnKey:s,operator:d,value:S.trim()}):f(s,null),w(!1)},V=()=>{F(""),m("contains"),f(s,null),w(!1)},q=!!g;return e.jsx(_e,{className:he("px-2",b),children:e.jsxs("div",{className:"flex items-center gap-0.5",children:[e.jsx("span",{className:"flex-1 truncate text-xs font-medium",children:l}),I&&e.jsx(N,{variant:"ghost",size:"icon",className:"h-5 w-5 flex-shrink-0",onClick:y=>{y.stopPropagation(),i(s)},title:"Sort",children:_==="ASC"?e.jsx(At,{className:"h-3 w-3 text-primary"}):_==="DESC"?e.jsx(es,{className:"h-3 w-3 text-primary"}):e.jsx(At,{className:"h-3 w-3 text-muted-foreground/40"})}),T&&e.jsxs(Ks,{open:o,onOpenChange:w,children:[e.jsx(Os,{asChild:!0,children:e.jsx(N,{variant:"ghost",size:"icon",className:he("h-5 w-5 flex-shrink-0",q&&"text-primary"),onClick:y=>y.stopPropagation(),title:"Filter",children:e.jsx(Gs,{className:he("h-3 w-3",q?"text-primary":"text-muted-foreground/40")})})}),e.jsx($s,{className:"w-64 p-3",align:"start",onClick:y=>y.stopPropagation(),children:e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"text-sm font-medium",children:["Filter: ",l]}),e.jsxs(re,{value:d,onValueChange:y=>m(y),children:[e.jsx(ie,{className:"h-8 text-sm",children:e.jsx(ne,{})}),e.jsx(le,{children:Ha.map(y=>e.jsx(J,{value:y.value,children:y.label},y.value))})]}),e.jsx(te,{placeholder:"Filter value...",value:S,onChange:y=>F(y.target.value),className:"h-8 text-sm",onKeyDown:y=>{y.key==="Enter"&&P()}}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(N,{size:"sm",className:"flex-1 h-7 text-xs",onClick:P,children:"Apply"}),q&&e.jsx(N,{size:"sm",variant:"outline",className:"h-7 text-xs",onClick:V,children:e.jsx(kt,{className:"h-3 w-3"})})]})]})})]})]})})},Wa=()=>{const{requests:s,loading:l,approveRequest:_,rejectRequest:i,deleteRequest:g,refetch:f}=Zt(),{processedItems:b,handleSort:I,getSortDirection:T,setColumnFilter:o,getColumnFilter:w}=ps({items:s}),{paginatedItems:d,page:m,setPage:S,pageSize:F,setPageSize:P,totalPages:V,totalCount:q,filteredCount:y,searchQuery:t,setSearchQuery:p}=Ms({items:b,searchFields:["list_name","requested_value","requested_by_email","status"],defaultPageSize:10}),D=h=>{switch(h){case"pending":return e.jsx(se,{variant:"outline",className:"bg-yellow-500/10 text-yellow-600 border-yellow-500/30",children:"Pending"});case"approved":return e.jsx(se,{variant:"outline",className:"bg-green-500/10 text-green-600 border-green-500/30",children:"Approved"});case"rejected":return e.jsx(se,{variant:"outline",className:"bg-red-500/10 text-red-600 border-red-500/30",children:"Rejected"});default:return e.jsx(se,{variant:"outline",children:h})}};return l?e.jsx("div",{className:"flex items-center justify-center py-12",children:e.jsx(Et,{className:"h-6 w-6 animate-spin text-muted-foreground"})}):e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx("h3",{className:"text-lg font-semibold",children:"List Value Requests"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Review and approve requests for new dropdown values"})]}),e.jsxs(N,{variant:"outline",size:"sm",onClick:f,children:[e.jsx(Et,{className:"h-4 w-4 mr-2"}),"Refresh"]})]}),s.length===0?e.jsx("div",{className:"text-center py-12 text-muted-foreground border rounded-lg",children:"No value requests found"}):e.jsx("div",{className:"border rounded-lg overflow-hidden",children:e.jsxs(ft,{children:[e.jsx(_t,{children:e.jsxs(Oe,{children:[e.jsx(ke,{columnKey:"list_name",label:"List Name",sortDirection:T("list_name"),onSort:I,filter:w("list_name"),onFilterChange:o}),e.jsx(ke,{columnKey:"requested_value",label:"Requested Value",sortDirection:T("requested_value"),onSort:I,filter:w("requested_value"),onFilterChange:o}),e.jsx(ke,{columnKey:"requested_by_email",label:"Requested By",sortDirection:T("requested_by_email"),onSort:I,filter:w("requested_by_email"),onFilterChange:o}),e.jsx(ke,{columnKey:"created_at",label:"Requested At",sortDirection:T("created_at"),onSort:I,filterable:!1,onFilterChange:o}),e.jsx(ke,{columnKey:"status",label:"Status",sortDirection:T("status"),onSort:I,filter:w("status"),onFilterChange:o}),e.jsx(ke,{columnKey:"actions",label:"Actions",sortable:!1,filterable:!1,sortDirection:null,onSort:I,onFilterChange:o,className:"text-right"})]})}),e.jsx(yt,{children:d.map(h=>e.jsxs(Oe,{children:[e.jsx(ee,{className:"font-medium",children:h.list_name}),e.jsx(ee,{children:e.jsx("span",{className:"font-mono text-sm bg-muted px-2 py-0.5 rounded",children:h.requested_value})}),e.jsx(ee,{children:h.requested_by_email||h.requested_by.slice(0,8)}),e.jsx(ee,{className:"text-muted-foreground",children:ns(new Date(h.created_at),"MMM d, yyyy h:mm a")}),e.jsx(ee,{children:D(h.status)}),e.jsx(ee,{className:"text-right",children:e.jsxs("div",{className:"flex items-center justify-end gap-1",children:[h.status==="pending"&&e.jsxs(e.Fragment,{children:[e.jsx(N,{variant:"ghost",size:"icon",className:"h-8 w-8 text-green-600 hover:text-green-700 hover:bg-green-50",onClick:()=>
26_(h.id),title:"Approve",children:e.jsx(Nt,{className:"h-4 w-4"})}),e.jsx(N,{variant:"ghost",size:"icon",className:"h-8 w-8 text-red-600 hover:text-red-700 hover:bg-red-50",onClick:()=>i(h.id),title:"Reject",children:e.jsx(kt,{className:"h-4 w-4"})})]}),e.jsx(N,{variant:"ghost",size:"icon",className:"h-8 w-8 text-muted-foreground hover:text-destructive",onClick:()=>g(h.id),title:"Delete",children:e.jsx($e,{className:"h-4 w-4"})})]})})]},h.id))})]})}),e.jsx(Vs,{page:m,totalPages:V,pageSize:F,totalCount:q,filteredCount:y,searchQuery:t,searchPlaceholder:"Search requests...",onPageChange:S,onPageSizeChange:P,onSearchChange:p})]})};function Ja({item:s,idx:l,onEdit:_,onInactivate:i,onDelete:g,onRestore:f}){const{attributes:b,listeners:I,setNodeRef:T,transform:o,transition:w,isDragging:d}=Xs({id:s.id}),m={transform:ea.Transform.toString(o),transition:w};return e.jsxs("div",{ref:T,style:m,className:he("grid items-center px-4 py-2 hover:bg-accent/50 group",d&&"opacity-40 bg-muted/30",!s.is_active&&"opacity-50",l%2===0?"bg-black/[0.04] dark:bg-white/[0.04]":""),style:{...m,gridTemplateColumns:"16px 1fr 80px 28px 80px"},children:[e.jsx("button",{...b,...I,className:"cursor-grab active:cursor-grabbing",children:e.jsx(wt,{className:"h-3 w-3 text-muted-foreground/30"})}),e.jsx("span",{className:"text-sm font-medium truncate min-w-0",children:s.display_label||s.list_value}),e.jsx("span",{className:"text-[11px] text-muted-foreground truncate",children:s.display_label&&s.display_label!==s.list_value?s.list_value:""}),e.jsx("span",{className:"text-center",children:!s.is_active&&e.jsx("span",{className:"text-[9px] font-semibold px-1 rounded bg-muted text-muted-foreground",children:"off"})}),e.jsxs("div",{className:"flex justify-end gap-0.5 opacity-0 group-hover:opacity-100",children:[e.jsx(N,{variant:"ghost",size:"icon",className:"h-6 w-6",onClick:()=>_(s),title:"Edit",children:e.jsx(We,{className:"h-3 w-3"})}),s.is_active?e.jsxs(e.Fragment,{children:[e.jsx(N,{variant:"ghost",size:"icon",className:"h-6 w-6",onClick:()=>i(s),title:"Inactivate",disabled:s.is_system,children:e.jsx(os,{className:"h-3 w-3"})}),e.jsx(N,{variant:"ghost",size:"icon",className:"h-6 w-6 text-destructive",onClick:()=>g(s),title:s.is_system?"System values cannot be deleted":"Delete",disabled:s.is_system,children:e.jsx($e,{className:"h-3 w-3"})})]}):e.jsx(N,{variant:"ghost",size:"icon",className:"h-6 w-6 text-primary",onClick:()=>f(s),title:"Restore",children:e.jsx(is,{className:"h-3 w-3"})})]})]})}const Ct={list_value:"",display_label:"",display_order:0};function Ya(){const{allLists:s,listNames:l,isLoading:_,addListItem:i,updateListItem:g,deleteListItem:f,permanentlyDeleteListItem:b,restoreListItem:I,bulkUpdateDisplayOrder:T}=Xt(),[o,w]=c.useState(""),[d,m]=c.useState(!1),[S,F]=c.useState(!1),[P,V]=c.useState(null),[q,y]=c.useState(!1),[t,p]=c.useState(""),[D,h]=c.useState(""),[M,Q]=c.useState(!1),[E,X]=c.useState(null),[x,r]=c.useState(Ct),[j,n]=c.useState(!1),R=Bs(Pt(Hs),Pt(Qs,{coordinateGetter:Us})),a=c.useMemo(()=>o?s.filter(O=>O.list_name===o&&(d||O.is_active)).sort((O,ue)=>O.display_order-ue.display_order):[],[s,o,d]),k=()=>{const O=s.filter(ue=>ue.list_name===o);return O.length===0?0:Math.max(...O.map(ue=>ue.display_order))+1},Y=()=>{if(!o){L.error("Select a list first");return}X(null),r({...Ct,display_order:k()}),F(!0)},Z=O=>{X(O),r({list_value:O.list_value,display_label:O.display_label||"",display_order:O.display_order}),F(!0)},A=async()=>{if(!x.list_value.trim()){L.error("Value key is required");return}n(!0);try{E?(await g.mutateAsync({id:E.id,updates:{list_value:x.list_value,display_label:x.display_label||x.list_value,display_order:x.display_order}}),L.success("Value updated")):(await i.mutateAsync({list_name:o,list_value:x.list_value,display_label:x.display_label||x.list_value,display_order:x.display_order,is_active:!0}),L.success("Value added")),F(!1),X(null),r(Ct)}catch(O){const ue=O instanceof Error?O.message:"";L.error(ue.includes("duplicate")?"A value with this key already exists":"Failed to save value")}finally{n(!1)}},G=async O=>{try{await f.mutateAsync(O.id),L.success("Value inactivated")}catch{L.error("Failed to inactivate")}},C=async()=>
26{if(P){try{await b.mutateAsync(P.id),L.success("Value permanently deleted")}catch{L.error("Failed to delete")}V(null)}},$=async O=>{try{await I.mutateAsync(O.id),L.success("Value restored")}catch{L.error("Failed to restore")}},ye=async O=>{const{active:ue,over:xe}=O;if(!xe||ue.id===xe.id)return;const Ve=a.findIndex(Le=>Le.id===ue.id),Je=a.findIndex(Le=>Le.id===xe.id),et=ta(a,Ve,Je).map((Le,v)=>({id:Le.id,display_order:v}));try{await T.mutateAsync(et)}catch{L.error("Failed to reorder")}},ce=async()=>{if(a.length===0)return;const ue=[...a].sort((xe,Ve)=>(xe.display_label||xe.list_value).toLowerCase().localeCompare((Ve.display_label||Ve.list_value).toLowerCase())).map((xe,Ve)=>({id:xe.id,display_order:Ve}));try{await T.mutateAsync(ue),L.success("Sorted")}catch{L.error("Failed to sort")}},Ae=async()=>{const O=t.trim().toLowerCase().replace(/\s+/g,"_");if(!O){L.error("List name is required");return}if(l.includes(O)){L.error("List already exists");return}Q(!0);try{await i.mutateAsync({list_name:O,list_value:"__placeholder__",display_label:D.trim()||t.trim(),display_order:0,is_active:!1}),L.success(`List "${D.trim()||t.trim()}" created`),w(O),y(!1),p(""),h("")}catch{L.error("Failed to create list")}finally{Q(!1)}};return _?e.jsx("div",{className:"py-8 text-center text-sm text-muted-foreground",children:"Loadingâ¦"}):e.jsxs("div",{className:"flex gap-4 h-[calc(100vh-16rem)]",children:[e.jsxs("div",{className:"w-56 flex-shrink-0 border rounded-lg flex flex-col",children:[e.jsxs("div",{className:"flex items-center justify-between px-3 py-2.5 border-b",children:[e.jsx("span",{className:"text-xs font-medium text-muted-foreground",children:"Lists"}),e.jsxs(N,{variant:"ghost",size:"sm",className:"h-6 text-xs text-primary gap-1",onClick:()=>{p(""),h(""),y(!0)},children:[e.jsx(Ne,{className:"h-3 w-3"})," New"]})]}),e.jsx("div",{className:"flex-1 overflow-auto",children:l.length===0?e.jsx("p",{className:"text-xs text-muted-foreground px-3 py-4",children:"No lists yet."}):l.map(O=>{const ue=s.filter(xe=>xe.list_name===O&&xe.is_active).length;return e.jsxs("button",{className:he("flex items-center gap-2 w-full px-3 py-2 text-left text-sm hover:bg-muted/30",o===O&&"bg-primary/10 text-primary font-medium"),onClick:()=>w(O),children:[e.jsx("span",{className:"flex-1 truncate",children:O.replace(/_/g," ").replace(/\b\w/g,xe=>xe.toUpperCase())}),e.jsx("span",{className:"text-xs text-muted-foreground/60",children:ue})]},O)})}),e.jsxs("div",{className:"px-3 py-2 border-t text-[11px] text-muted-foreground",children:[l.length," lists. ",s.filter(O=>O.is_active).length," active values."]})]}),e.jsx("div",{className:"flex-1 border rounded-lg flex flex-col",children:o?e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"flex items-center justify-between px-4 py-2.5 border-b",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsxs("span",{className:"text-xs text-muted-foreground",children:[a.length," values",!d&&s.filter(O=>O.list_name===o&&!O.is_active).length>0?` (${s.filter(O=>O.list_name===o&&!O.is_active).length} inactive hidden)`:""]}),e.jsxs("label",{className:"flex items-center gap-1.5 text-xs text-muted-foreground",children:[e.jsx(Ce,{checked:d,onCheckedChange:m,className:"scale-75"}),"Inactive"]})]}),e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsxs(N,{variant:"ghost",size:"sm",className:"h-7 text-xs gap-1",onClick:ce,disabled:a.length===0,children:[e.jsx(Ca,{className:"h-3.5 w-3.5"})," AâZ"]}),e.jsxs(N,{size:"sm",className:"h-7 text-xs gap-1",onClick:Y,children:[e.jsx(Ne,{className:"h-3.5 w-3.5"})," Add Value"]})]})]}),e.jsx("div",{className:"flex-1 overflow-auto",children:a.length===0?e.jsx("div",{className:"py-12 text-center text-sm text-muted-foreground",children:d?"No values in this list.":"No active values."}):e.jsx(Ws,{sensors:R,collisionDetection:Js,onDragEnd:ye,children:e.jsx(Ys,{items:a.map(O=>O.id),strategy:Zs,children:a.map((O,ue)=>e.jsx(Ja,{item:O,idx:ue,onEdit:Z,onInactivate:G,onDelete:V,onRestore:$},O.id))})})})]}):e.jsx("div",{className:"flex-1 flex items-center justify-center text-sm text-muted-foreground",children:"Select a list to manage its values."})}),e.jsx(Ee,{open:S,onOpenChange:F,children:e.jsxs(Pe,{className:"w-[400px] sm:max-w-[400px]",children:[e.jsx(ze,{children:e.jsx(Me,{children:E?"Edit Value":"Add Value"})}),e.jsxs("div",{className:"space-y-4 py-4",children:[e.jsxs("div",{className:"space-y-1",children:[e.jsx(W,{className:"text-xs font-semibold uppercase text-muted-foreground",children:"Key"}),e.jsx(te,{value:x.list_value,onChange:O=>r({...x,list_value:O.target.value}),placeholder:"e.g. my_value",className:"font-mono text-sm",disabled:!!E}),!E&&e.jsx("p",{className:"text-[10px] text-muted-foreground",children:"Cannot change after creation."})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx(W,{className:"text-xs font-semibold uppercase text-muted-foreground",children:"Display Label"}),e.jsx(te,{value:x.display_label,onChange:O=>r({...x,display_label:O.target.value}),placeholder:"e.g. My Value"})]})]}),e.jsxs(qe,{className:"border-t pt-4",children:[e.jsx(N,{variant:"outline",onClick:()=>F(!1),children:"Cancel"}),e.jsx(N,{onClick:A,disabled:j||!x.list_value.trim(),children:j?"Savingâ¦":E?"Save":"Create"})]})]})}),e.jsx(it,{open:!!P,onOpenChange:O=>{O||V(null)},children:e.jsxs(nt,{children:[e.jsxs(lt,{children:[e.jsxs(ot,{className:"flex items-center gap-2",children:[e.jsx(xt,{className:"h-5 w-5 text-destructive"}),"Delete â",(P==null?void 0:P.display_label)||(P==null?void 0:P.list_value),"â?"]}),e.jsx(ct,{children:"This permanently removes the value. To hide it without deleting, use inactivate instead."})]}),e.jsxs(dt,{children:[e.jsx(ut,{children:"Cancel"}),e.jsx(pt,{className:"bg-destructive hover:bg-destructive/90",onClick:C,children:"Delete Permanently"})]})]})}),e.jsx(Ee,{open:q,onOpenChange:y,children:e.jsxs(Pe,{className:"w-[400px] sm:max-w-[400px]",children:[e.jsx(ze,{children:e.jsx(Me,{children:"New List"})}),e.jsxs("div",{className:"space-y-4 py-4",children:[e.jsxs("div",{className:"space-y-1",children:[e.jsx(W,{className:"text-xs font-semibold uppercase text-muted-foreground",children:"Name"}),e.jsx(te,{value:t,onChange:O=>p(O.target.value),placeholder:"e.g. Finish Type",autoFocus:!0,onKeyDown:O=>{O.key==="Enter"&&(O.preventDefault(),Ae())}}),e.jsx("p",{className:"text-[10px] text-muted-foreground",children:"Stored as snake_case."})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx(W,{className:"text-xs font-semibold uppercase text-muted-foreground",children:"Display Label"}),e.jsx(te,{value:D,onChange:O=>h(O.target.value),placeholder:"e.g. Finish Type"})]})]}),e.jsxs(qe,{className:"border-t pt-4",children:[e.jsx(N,{variant:"outline",onClick:()=>y(!1),children:"Cancel"}),e.jsx(N,{onClick:Ae,disabled:M||!t.trim(),children:M?"Creatingâ¦":"Create List"})]})]})})]})}const Za=[{value:"professional",label:"Professional"},{value:"casual",label:"Casual"},{value:"technical",label:"Technical"},{value:"luxury",label:"Luxury"},{value:"playful",label:"Playful"},{value:"concise",label:"Concise"}],Xa=[{value:"descriptions",label:"Descriptions"},{value:"feature_bullets",label:"Feature Bullets"},{value:"seo_text",label:"SEO Text"},{value:"tags",label:"Tags / Keywords"},{value:"other",label:"Other"}],ms=c.forwardRef(({onStateChange:s},l)=>{var j,n,R;const{currentOrg:_}=Se(),i=(_==null?void 0:_.id)??null,{attributes:g}=Xe("product"),{attributes:f}=Xe("variant"),b=c.useMemo(()=>[...g,...f],[g,f]),{prompts:I,isLoading:T,upsert:o,remove:w,toggle:d,isSaving:m}=sa(i),[S,F]=c.useState(""),[P,V]=c.useState(null),[q,y]=c.useState(null),[t,p]=c.useState(!1),D=c.useMemo(()=>{const a=new Map;for(const k of b)a.set(k.id,k);return a},[b]),h=c.useMemo(()=>new Set(I.map(a=>a.attribute_id)),[I]),M=c.useMemo(()=>b.filter(a=>!h.has(a.id)&&a.data_type!=="bool").filter(a=>{var k;return!S||((k=a.label)==null?void 0:k.toLowerCase().includes(S.toLowerCase()))||a.key.toLowerCase().includes(S.toLowerCase())}),[b,h,S]);c.useImperativeHandle(l,()=>({hasUnsavedChanges:()=>t,save:async()=>{q&&(o(q),p(!1),s==null||s(!1))}}));const Q=c.useCallback(()=>{p(!0),s==null||s(!0)},[s]),E=a=>{const k=I.find(Y=>Y.attribute_id===a);k&&y({attribute_id:k.attribute_id,prompt_template:k.prompt_template||"",tone:k.tone||"professional",content_type:k.content_type||"descriptions",min_chars:k.min_chars,max_chars:k.max_chars,include_primary_image:k.include_primary_image??!1,context_attributes:k.context_attributes??[],is_enabled:k.is_enabled??!0}),V(a),p(!1),s==null||s(!1)},X=a=>{const k={attribute_id:a.id,prompt_template:`Write compelling ${a.label||a.key} content for "{title}" by {vendor}. Product type: {product_type}.`,tone:"professional",content_type:a.data_type==="array"?"tags":"descriptions",min_chars:null,max_chars:null,include_primary_image:!1,
26context_attributes:[],is_enabled:!0};o(k),V(a.id),y(k)},x=()=>{q&&(o(q),p(!1),s==null||s(!1))},r=a=>{w(a),P===a&&(V(null),y(null))};return T?e.jsx("div",{className:"p-4 text-sm text-muted-foreground",children:"Loading field configsâ¦"}):e.jsxs("div",{className:"flex h-full",children:[e.jsxs("div",{className:"w-[260px] border-r flex flex-col",children:[e.jsxs("div",{className:"p-3 border-b",children:[e.jsxs("h3",{className:"text-sm font-semibold flex items-center gap-1.5",children:[e.jsx(gt,{className:"h-3.5 w-3.5 text-primary"}),"AI-Generated Fields"]}),e.jsxs("p",{className:"text-[10px] text-muted-foreground mt-0.5",children:[I.length," field",I.length!==1?"s":""," configured, ",I.filter(a=>a.is_enabled).length," enabled"]})]}),e.jsxs("div",{className:"flex-1 overflow-y-auto",children:[I.map(a=>{const k=D.get(a.attribute_id),Y=(k==null?void 0:k.label)||(k==null?void 0:k.key)||a.field_name||a.attribute_id.slice(0,8),Z=k?g.includes(k)?"Product":"Variant":"?";return e.jsxs("div",{className:he("px-3 py-2 cursor-pointer border-b border-border/50 hover:bg-muted/50 group",P===a.attribute_id&&"bg-primary/10"),onClick:()=>E(a.attribute_id),children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("span",{className:"text-sm font-medium truncate",children:Y}),e.jsx("div",{className:"flex items-center gap-1",children:e.jsx(se,{variant:a.is_enabled?"default":"secondary",className:"text-[9px] px-1 py-0",children:a.is_enabled?"On":"Off"})})]}),e.jsxs("div",{className:"flex items-center gap-2 mt-0.5",children:[e.jsx("span",{className:"text-[10px] text-muted-foreground",children:Z}),e.jsx("span",{className:"text-[10px] text-muted-foreground",children:"·"}),e.jsx("span",{className:"text-[10px] text-muted-foreground capitalize",children:a.tone||"professional"})]})]},a.attribute_id)}),e.jsxs("div",{className:"p-2 border-t",children:[e.jsxs("div",{className:"relative mb-2",children:[e.jsx(bs,{className:"absolute left-2 top-2 h-3.5 w-3.5 text-muted-foreground"}),e.jsx(te,{placeholder:"Search attributesâ¦",className:"h-8 pl-7 text-xs",value:S,onChange:a=>F(a.target.value)})]}),e.jsxs("div",{className:"max-h-[160px] overflow-y-auto space-y-0.5",children:[M.slice(0,20).map(a=>e.jsxs("button",{className:"w-full text-left px-2 py-1.5 text-xs rounded hover:bg-muted/70 flex items-center justify-between group",onClick:()=>X(a),children:[e.jsx("span",{className:"truncate",children:a.label||a.key}),e.jsx(Ne,{className:"h-3 w-3 text-muted-foreground opacity-0 group-hover:opacity-100"})]},a.id)),M.length===0&&e.jsx("p",{className:"text-[10px] text-muted-foreground px-2 py-1",children:"All attributes configured"})]})]})]})]}),e.jsx("div",{className:"flex-1 p-4 overflow-y-auto",children:q?e.jsxs("div",{className:"space-y-5 max-w-lg",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx("h3",{className:"text-sm font-semibold",children:((j=D.get(q.attribute_id))==null?void 0:j.label)||q.attribute_id.slice(0,8)}),e.jsxs("p",{className:"text-[10px] text-muted-foreground",children:[(n=D.get(q.attribute_id))==null?void 0:n.key," · ",(R=D.get(q.attribute_id))==null?void 0:R.data_type]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Ce,{checked:q.is_enabled,onCheckedChange:a=>{y(k=>k&&{...k,is_enabled:a}),Q()}}),e.jsx(N,{variant:"ghost",size:"icon",className:"h-7 w-7 text-destructive",onClick:()=>r(q.attribute_id),title:"Remove from AI generation",children:e.jsx($e,{className:"h-3.5 w-3.5"})})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(W,{className:"text-xs font-semibold uppercase text-muted-foreground",children:"Tone"}),e.jsxs(re,{value:q.tone,onValueChange:a=>{y(k=>k&&{...k,tone:a}),Q()},children:[e.jsx(ie,{className:"h-8 text-xs",children:e.jsx(ne,{})}),e.jsx(le,{children:Za.map(a=>e.jsx(J,{value:a.value,children:a.label},a.value))})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(W,{className:"text-xs font-semibold uppercase text-muted-foreground",children:"Content Type"}),e.jsxs(re,{value:q.content_type,onValueChange:a=>{y(k=>k&&{...k,content_type:a}),Q()},children:[e.jsx(ie,{className:"h-8 text-xs",children:e.jsx(ne,{})}),e.jsx(le,{children:Xa.map(a=>e.jsx(J,{value:a.value,children:a.label},a.value))})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(W,{className:"text-xs font-semibold uppercase text-muted-foreground",children:"Prompt Template"}),e.jsx(Lt,{className:"text-xs min-h-[80px] font-mono",value:q.prompt_template,onChange:a=>{y(k=>k&&{...k,prompt_template:a.target.value}),Q()},placeholder:'Write compelling content for "{title}" by {vendor}...'}),e.jsxs("p",{className:"text-[10px] text-muted-foreground",children:["Variables: ","{title}",", ","{vendor}",", ","{product_type}",", ","{category}"]})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(W,{className:"text-xs font-semibold uppercase text-muted-foreground",children:"Min Characters"}),e.jsx(te,{type:"number",className:"h-8 text-xs",value:q.min_chars??"",onChange:a=>{y(k=>k&&{...k,min_chars:a.target.value?parseInt(a.target.value):null}),Q()},placeholder:"No minimum"})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(W,{className:"text-xs font-semibold uppercase text-muted-foreground",children:"Max Characters"}),e.jsx(te,{type:"number",className:"h-8 text-xs",value:q.max_chars??"",onChange:a=>{y(k=>k&&{...k,max_chars:a.target.value?parseInt(a.target.value):null}),Q()},placeholder:"No maximum"})]})]}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx(W,{className:"text-sm",children:"Include product image"}),e.jsx("p",{className:"text-[10px] text-muted-foreground",children:"Send the hero image to the AI for richer context."})]}),e.jsx(Ce,{checked:q.include_primary_image,onCheckedChange:a=>{y(k=>k&&{...k,include_primary_image:a}),Q()}})]}),e.jsxs("div",{className:"space-y-1.5 pt-1",children:[e.jsx(W,{className:"text-sm",children:"Context attributes"}),e.jsxs("p",{className:"text-[10px] text-muted-foreground",children:["Include these attributes' values in the prompt as context. Reference them in the template with ",e.jsx("code",{children:"{attribute_key}"}),"."]}),e.jsx("div",{className:"flex flex-wrap gap-1.5 max-h-40 overflow-y-auto rounded-md border border-border/60 p-2",children:b.filter(a=>a.id!==q.attribute_id).map(a=>{const k=q.context_attributes.includes(a.key);return e.jsx("button",{type:"button",onClick:()=>{y(Y=>{if(!Y)return Y;const Z=new Set(Y.context_attributes);return Z.has(a.key)?Z.delete(a.key):Z.add(a.key),{...Y,context_attributes:[...Z]}}),Q()},className:`text-[11px] px-2 py-0.5 rounded-full border transition-colors ${k?"bg-primary text-primary-foreground border-primary":"bg-card text-muted-foreground border-border/60 hover:border-primary/40 hover:text-foreground"}`,children:a.label||a.key},a.id)})})]}),e.jsxs("div",{className:"pt-2 border-t flex justify-end gap-2",children:[e.jsx(N,{variant:"outline",size:"sm",onClick:()=>E(q.attribute_id),children:"Revert"}),e.jsx(N,{size:"sm",onClick:x,disabled:!t||m,children:m?"Savingâ¦":"Save Field Config"})]})]}):e.jsx("div",{className:"flex items-center justify-center h-full text-sm text-muted-foreground",children:"Select a field to configure, or add one from the list."})})]})});ms.displayName="AIContentGenerationSettings";const er=[{value:"15",label:"Every 15 minutes"},{value:"30",label:"Every 30 minutes"},{value:"60",label:"Every hour"},{value:"120",label:"Every 2 hours"},{value:"360",label:"Every 6 hours"},{value:"720",label:"Every 12 hours"},{value:"1440",label:"Every 24 hours"},{value:"0",label:"Disabled"}],tr=()=>{const{currentOrg:s}=Se(),[l,_]=c.useState("60"),[i,g]=c.useState(!0),[f,b]=c.useState(!1),[I,T]=c.useState(null);c.useEffect(()=>{if(!(s!=null&&s.id))return;(async()=>{g(!0);const{data:d}=await U.from("org_settings").select("setting_value").eq("org_id",s.id).eq("setting_key","publish_rule_interval_minutes").maybeSingle();d&&_(d.setting_value);const{data:m}=await U.from("org_settings").select("setting_value").eq("org_id",s.id).eq("setting_key","publish_rule_last_run").maybeSingle();m&&T(m.setting_value),g(!1)})()},[s==null?void 0:s.id]);const o=async()=>
26{if(s!=null&&s.id){b(!0);try{const{error:w}=await U.from("org_settings").upsert({org_id:s.id,setting_key:"publish_rule_interval_minutes",setting_value:l},{onConflict:"org_id,setting_key"});if(w)throw w;zt.success("Schedule saved")}catch(w){zt.error("Failed to save: "+w.message)}finally{b(!1)}}};return i?e.jsx(me,{className:"border-border/50 bg-card/50",children:e.jsx(Te,{className:"py-8 flex justify-center",children:e.jsx(Ze,{className:"h-5 w-5 animate-spin text-muted-foreground"})})}):e.jsxs(me,{className:"border-border/50 bg-card/50",children:[e.jsxs(Be,{children:[e.jsxs(Ue,{className:"flex items-center gap-2",children:[e.jsx(Da,{className:"h-5 w-5"}),"Publish Rule Auto-Run"]}),e.jsx(at,{children:"Configure how often publish rules are automatically evaluated to assign products to hierarchy nodes."})]}),e.jsxs(Te,{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-end gap-4",children:[e.jsxs("div",{className:"space-y-2 flex-1 max-w-xs",children:[e.jsx(W,{htmlFor:"rule-interval",children:"Run Interval"}),e.jsxs(re,{value:l,onValueChange:_,children:[e.jsx(ie,{id:"rule-interval",children:e.jsx(ne,{})}),e.jsx(le,{children:er.map(w=>e.jsx(J,{value:w.value,children:w.label},w.value))})]})]}),e.jsxs(N,{onClick:o,disabled:f,children:[f?e.jsx(Ze,{className:"h-4 w-4 mr-1 animate-spin"}):e.jsx(aa,{className:"h-4 w-4 mr-1"}),"Save"]})]}),I&&e.jsxs("div",{className:"flex items-center gap-2 text-xs text-muted-foreground",children:[e.jsx("span",{children:"Last auto-run:"}),e.jsx(se,{variant:"outline",className:"text-xs",children:new Date(I).toLocaleString()})]}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"The system automatically evaluates all active publish rules at the configured interval and assigns matching products to their target nodes."})]})]})};function sr(){const{rows:s,totalCount:l,loading:_,page:i,setPage:g,pageSize:f,setPageSize:b,filters:I,setFilters:T,markProcessed:o}=ra(),[w,d]=c.useState(new Set),{processedItems:m,handleSort:S,getSortDirection:F,setColumnFilter:P,getColumnFilter:V}=ps({items:s}),q=Math.max(1,Math.ceil(l/f)),y=h=>{d(M=>{const Q=new Set(M);return Q.has(h)?Q.delete(h):Q.add(h),Q})},t=async()=>{w.size!==0&&(await o(Array.from(w)),d(new Set))},p=h=>{T({...I,...h}),g(0)},D=h=>{switch(h){case"Create":return e.jsx(se,{className:"bg-primary text-primary-foreground",children:"Create"});case"Update":return e.jsx(se,{variant:"secondary",children:"Update"});case"Delete":return e.jsx(se,{variant:"destructive",children:"Delete"});default:return e.jsx(se,{variant:"secondary",children:h})}};return e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex flex-wrap gap-3 items-end",children:[e.jsxs("div",{className:"space-y-1",children:[e.jsx("label",{className:"text-xs font-medium text-muted-foreground",children:"Change Type"}),e.jsxs(re,{value:I.changeType,onValueChange:h=>p({changeType:h}),children:[e.jsx(ie,{className:"w-[130px]",children:e.jsx(ne,{})}),e.jsxs(le,{children:[e.jsx(J,{value:"All",children:"All"}),e.jsx(J,{value:"Create",children:"Create"}),e.jsx(J,{value:"Update",children:"Update"}),e.jsx(J,{value:"Delete",children:"Delete"})]})]})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx("label",{className:"text-xs font-medium text-muted-foreground",children:"Status"}),e.jsxs(re,{value:I.processedStatus,onValueChange:h=>p({processedStatus:h}),children:[e.jsx(ie,{className:"w-[140px]",children:e.jsx(ne,{})}),e.jsxs(le,{children:[e.jsx(J,{value:"All",children:"All"}),e.jsx(J,{value:"Processed",children:"Processed"}),e.jsx(J,{value:"Unprocessed",children:"Unprocessed"})]})]})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx("label",{className:"text-xs font-medium text-muted-foreground",children:"Product ID"}),e.jsx(te,{placeholder:"Filter by product ID...",value:I.productSearch,onChange:h=>p({productSearch:h.target.value}),className:"w-[260px]"})]}),w.size>0&&e.jsxs(N,{size:"sm",onClick:t,className:"gap-1",children:[e.jsx(Nt,{className:"h-3 w-3"})," Mark ",w.size," Processed"]})]}),_?e.jsx("div",{className:"flex justify-center py-12",children:e.jsx(Ze,{className:"h-6 w-6 animate-spin text-muted-foreground"})}):s.length===0?e.jsx("p",{className:"text-center py-12 text-muted-foreground",children:"No events found."}):e.jsxs(ft,{children:[e.jsx(_t,{children:e.jsxs(Oe,{children:[e.jsx(ke,{columnKey:"select",label:"",sortable:!1,filterable:!1,sortDirection:null,onSort:S,onFilterChange:P,className:"w-8"}
26),e.jsx(ke,{columnKey:"changed_at",label:"Date / Time",sortDirection:F("changed_at"),onSort:S,filterable:!1,onFilterChange:P}),e.jsx(ke,{columnKey:"product_id",label:"Product ID",sortDirection:F("product_id"),onSort:S,filter:V("product_id"),onFilterChange:P}),e.jsx(ke,{columnKey:"node_ids",label:"Node ID(s)",sortable:!1,filterable:!1,sortDirection:null,onSort:S,onFilterChange:P}),e.jsx(ke,{columnKey:"change_type",label:"Type",sortDirection:F("change_type"),onSort:S,filter:V("change_type"),onFilterChange:P}),e.jsx(ke,{columnKey:"is_processed",label:"Processed",sortDirection:F("is_processed"),onSort:S,filter:V("is_processed"),onFilterChange:P}),e.jsx(ke,{columnKey:"details",label:"Details",sortDirection:F("details"),onSort:S,filter:V("details"),onFilterChange:P}),e.jsx(ke,{columnKey:"action",label:"",sortable:!1,filterable:!1,sortDirection:null,onSort:S,onFilterChange:P})]})}),e.jsx(yt,{children:m.map(h=>{var M,Q;return e.jsxs(Oe,{children:[e.jsx(ee,{children:e.jsx("input",{type:"checkbox",checked:w.has(h.id),onChange:()=>y(h.id),className:"rounded border-border"})}),e.jsx(ee,{className:"text-xs whitespace-nowrap",children:ns(new Date(h.changed_at),"yyyy-MM-dd HH:mm:ss")}),e.jsxs(ee,{className:"text-xs font-mono truncate max-w-[140px]",title:h.product_id||"",children:[(M=h.product_id)==null?void 0:M.slice(0,8),"..."]}),e.jsx(ee,{className:"text-xs font-mono truncate max-w-[180px]",title:(h.node_ids||[h.node_id]).filter(Boolean).join(", "),children:h.node_ids&&h.node_ids.length>0?`${h.node_ids.length} node${h.node_ids.length>1?"s":""}`:((Q=h.node_id)==null?void 0:Q.slice(0,8))+"..."||"â"}),e.jsx(ee,{children:D(h.change_type)}),e.jsx(ee,{children:h.is_processed?e.jsx(se,{variant:"secondary",children:"Yes"}):e.jsx(se,{variant:"outline",children:"No"})}),e.jsx(ee,{className:"text-xs text-muted-foreground max-w-[200px] truncate",children:h.details||"â"}),e.jsx(ee,{children:!h.is_processed&&e.jsx(N,{variant:"ghost",size:"sm",onClick:()=>o([h.id]),children:e.jsx(Nt,{className:"h-3 w-3"})})})]},h.id)})})]}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-2 text-sm text-muted-foreground",children:[e.jsx("span",{children:"Rows per page:"}),e.jsxs(re,{value:String(f),onValueChange:h=>{b(Number(h)),g(0)},children:[e.jsx(ie,{className:"w-[70px] h-8",children:e.jsx(ne,{})}),e.jsxs(le,{children:[e.jsx(J,{value:"10",children:"10"}),e.jsx(J,{value:"50",children:"50"}),e.jsx(J,{value:"100",children:"100"})]})]}),e.jsxs("span",{children:[l," total"]})]}),e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx(N,{variant:"outline",size:"icon",className:"h-8 w-8",disabled:i===0,onClick:()=>g(h=>h-1),children:e.jsx(ia,{className:"h-4 w-4"})}),e.jsxs("span",{className:"text-sm px-2",children:[i+1," / ",q]}),e.jsx(N,{variant:"outline",size:"icon",className:"h-8 w-8",disabled:i>=q-1,onClick:()=>g(h=>h+1),children:e.jsx(Tt,{className:"h-4 w-4"})})]})]})]})}const ar=()=>{const{attributes:s}=As(),{currentOrg:l}=Se(),_=Ge(),i=async n=>{const{error:R}=await U.rpc("pim_upsert_attribute",{p_org_id:l.id,p_repository_key:n.repositoryKey,p_key:n.key,p_label:n.label||n.key,p_data_type:n.dataType||"text",p_is_required_for_publish:n.isRequiredForPublish??!1,p_display_order:n.displayOrder??0,p_description:n.description||null,p_default_value:n.defaultValue||null,p_display_lines:n.displayLines??1,...n.attributeId?{p_attribute_id:n.attributeId}:{}});if(R)throw R;_.invalidateQueries({queryKey:["pim-schema"]})},g=(s||[]).filter(n=>n.category_scoped).map(n=>({id:n.id,attribute_name:n.attribute_name,display_label:n.display_label,data_type:n.data_type,level:n.table_name==="pim_variants"?"variant":"product",is_active:!0,is_required_for_publish:n.is_required_for_publish??!1,display_order:n.display_order??0,list_name:null,category_id:null})),{allLists:f,addListItem:b,updateListItem:I}=Xt(),T=c.useRef(null),[o,w]=c.useState(!1),[d,m]=c.useState([]),[S,F]=c.useState(null),[P,V]=c.useState(!1),q=f.filter(n=>n.list_name==="attribute_category"),y=n=>typeof n=="boolean"?n:typeof n=="string"?n.toLowerCase()==="true"||n==="1":typeof n=="number"?n===1:!1,t=n=>n==null?"":String(n),p=async()=>{const n=new la.Workbook,R=s.filter(C=>C.table_name==="pim_products").map(D);st(n,"Products",R);const a=s.filter(C=>C.table_name==="pim_variants").map(D);st(n,"Variants",a);const k=s.filter(C=>C.table_name==="media_assets").map(D);st(n,"Images",k);const Y=g.map(C=>({attribute_name:C.attribute_name,display_label:C.display_label||"",description:C.description||"",data_type:C.data_type,level:C.level,list_name:C.list_name||"",unit_list_name:C.unit_list_name||"",is_required:C.is_required,is_readonly:C.is_readonly,is_active:C.is_active,is_required_for_publish:C.is_required_for_publish,display_order:C.display_order,category_id:C.category_id||""}));st(n,"Category Specifics",Y);const Z=f.filter(C=>C.list_name!=="attribute_category").map(C=>({list_name:C.list_name,list_value:C.list_value,display_label:C.display_label||"",display_order:C.display_order,is_active:C.is_active,is_system:C.is_system??!1}));st(n,"Lists",Z);const A=q.map(C=>{const $=C.metadata;return{list_value:C.list_value,display_label:C.display_label||"",display_order:C.display_order,is_active:C.is_active,double_width:($==null?void 0:$.double_width)===!0}});st(n,"Categories",A),await oa(n,`data-model-export-${new Date().toISOString().split("T")[0]}.xlsx`);const G=R.length+a.length+k.length+Y.length+Z.length+A.length;L.success(`Exported ${G} rows across 6 sheets`)};function D(n){return{attribute_name:n.attribute_name,table_name:n.table_name,display_label:n.display_label||"",description:n.description||"",data_type:n.data_type,is_readonly:n.is_readonly,is_active:n.is_active,visible_by_default:n.visible_by_default,is_required_for_publish:n.is_required_for_publish,display_order:n.display_order,category_id:n.
26category_id||"",category_label:n.category_label||"",unit_list_name:n.unit_list_name||"",default_lines:n.default_lines,default_value:n.default_value||""}}const h=n=>{var k;const R=(k=n.target.files)==null?void 0:k[0];if(!R)return;const a=new FileReader;a.onload=async Y=>{var Z;try{const A=(Z=Y.target)==null?void 0:Z.result,G=await ca(A),C=Q(G);F(G),m(C),w(!0)}catch{L.error("Failed to read Excel file")}},a.readAsArrayBuffer(R),n.target.value=""},M=(n,R)=>da(n,R),Q=n=>{const R=[],a=[{sheet:"Products",tableName:"pim_products"},{sheet:"Variants",tableName:"pim_variants"},{sheet:"Images",tableName:"media_assets"}];for(const{sheet:A,tableName:G}of a){const C=M(n,A);for(const $ of C){`${G}${t($.attribute_name)}`;const ye=s.find(ce=>ce.table_name===G&&ce.attribute_name===t($.attribute_name));if(!ye)R.push({type:"add",sheet:A,name:t($.attribute_name),details:`New ${t($.data_type)} attribute`});else{const ce=E($,ye);ce.length&&R.push({type:"update",sheet:A,name:t($.attribute_name),details:`Update: ${ce.join(", ")}`})}}}const k=M(n,"Category Specifics");for(const A of k){const G=g.find(C=>C.attribute_name===t(A.attribute_name));if(!G)R.push({type:"add",sheet:"Category Specifics",name:t(A.attribute_name),details:`New ${t(A.data_type)} cat-specific attribute`});else{const C=X(A,G);C.length&&R.push({type:"update",sheet:"Category Specifics",name:t(A.attribute_name),details:`Update: ${C.join(", ")}`})}}const Y=M(n,"Lists");for(const A of Y){const G=f.find(C=>C.list_name===t(A.list_name)&&C.list_value===t(A.list_value)&&C.list_name!=="attribute_category");if(!G)R.push({type:"add",sheet:"Lists",name:`${t(A.list_name)}: ${t(A.list_value)}`,details:"New list value"});else{const C=[];t(A.display_label)!==(G.display_label||"")&&C.push("display_label"),Number(A.display_order)!==G.display_order&&C.push("display_order"),y(A.is_active)!==G.is_active&&C.push("is_active"),C.length&&R.push({type:"update",sheet:"Lists",name:`${t(A.list_name)}: ${t(A.list_value)}`,details:`Update: ${C.join(", ")}`})}}const Z=M(n,"Categories");for(const A of Z){const G=q.find(C=>C.list_value===t(A.list_value));if(!G)R.push({type:"add",sheet:"Categories",name:t(A.list_value),details:"New category"});else{const C=[];t(A.display_label)!==(G.display_label||"")&&C.push("display_label"),Number(A.display_order)!==G.display_order&&C.push("display_order"),y(A.is_active)!==G.is_active&&C.push("is_active");const $=G.metadata;y(A.double_width)!==(($==null?void 0:$.double_width)===!0)&&C.push("double_width"),C.length&&R.push({type:"update",sheet:"Categories",name:t(A.list_value),details:`Update: ${C.join(", ")}`})}}return R};function E(n,R){const a=[];return t(n.display_label)!==(R.display_label||"")&&a.push("display_label"),t(n.description)!==(R.description||"")&&a.push("description"),t(n.data_type)!==R.data_type&&a.push("data_type"),y(n.is_readonly)!==R.is_readonly&&a.push("is_readonly"),y(n.is_active)!==R.is_active&&a.push("is_active"),y(n.visible_by_default)!==R.visible_by_default&&a.push("visible_by_default"),y(n.is_required_for_publish)!==R.is_required_for_publish&&a.push("is_required_for_publish"),Number(n.display_order)!==R.display_order&&a.push("display_order"),t(n.unit_list_name)!==(R.unit_list_name||"")&&a.push("unit_list_name"),Number(n.default_lines)!==R.default_lines&&a.push("default_lines"),t(n.default_value)!==(R.default_value||"")&&a.push("default_value"),t(n.category_id)!==(R.category_id||"")&&a.push("category"),a}function X(n,R){const a=[];return t(n.display_label)!==(R.display_label||"")&&a.push("display_label"),t(n.description)!==(R.description||"")&&a.push("description"),t(n.data_type)!==R.data_type&&a.push("data_type"),t(n.level)!==R.level&&a.push("level"),t(n.list_name)!==(R.list_name||"")&&a.push("list_name"),t(n.unit_list_name)!==(R.unit_list_name||"")&&a.push("unit_list_name"),y(n.is_required)!==R.is_required&&a.push("is_required"),y(n.is_readonly)!==R.is_readonly&&a.push("is_readonly"),y(n.is_active)!==R.is_active&&a.push("is_active"),y(n.is_required_for_publish)!==R.is_required_for_publish&&a.push("is_required_for_publish"),Number(n.display_order)!==R.display_order&&a.push("display_order"),t(n.category_id)!==(R.category_id||"")&&a.push("category_id"),a}const x=async()=>
26{if(!S)return;V(!0);let n=0,R=0;try{const a=[{sheet:"Products",tableName:"pim_products"},{sheet:"Variants",tableName:"pim_variants"},{sheet:"Images",tableName:"media_assets"}];for(const{sheet:A,tableName:G}of a){const C=M(S,A);for(const $ of C){const ye=s.find(ce=>ce.table_name===G&&ce.attribute_name===t($.attribute_name));ye?E($,ye).length>0&&(await i({repositoryKey:G==="pim_variants"?"variant":"product",key:t($.attribute_name),label:t($.display_label)||t($.attribute_name),description:t($.description)||void 0,dataType:t($.data_type)||"text",displayOrder:Number($.display_order)||0,isRequiredForPublish:y($.is_required_for_publish),defaultValue:t($.default_value)||null,displayLines:Number($.default_lines)||1,attributeId:ye.id}),R++):(await i({repositoryKey:G==="pim_variants"?"variant":"product",key:t($.attribute_name),label:t($.display_label)||t($.attribute_name),description:t($.description)||void 0,dataType:t($.data_type)||"text",displayOrder:Number($.display_order)||0,isRequiredForPublish:y($.is_required_for_publish),defaultValue:t($.default_value)||null,displayLines:Number($.default_lines)||1}),n++)}}const k=M(S,"Category Specifics");for(const A of k){const G=g.find($=>$.attribute_name===t(A.attribute_name)),C=t(A.level)==="variant"?"variant":"product";G?X(A,G).length>0&&(await i({repositoryKey:C,key:t(A.attribute_name),label:t(A.display_label)||t(A.attribute_name),description:t(A.description)||void 0,dataType:t(A.data_type)||"text",displayOrder:Number(A.display_order)||0,isRequiredForPublish:y(A.is_required_for_publish),attributeId:G.id}),R++):(await i({repositoryKey:C,key:t(A.attribute_name),label:t(A.display_label)||t(A.attribute_name),description:t(A.description)||void 0,dataType:t(A.data_type)||"text",displayOrder:Number(A.display_order)||0,isRequiredForPublish:y(A.is_required_for_publish)}),n++)}const Y=M(S,"Lists");for(const A of Y){const G=f.find(C=>C.list_name===t(A.list_name)&&C.list_value===t(A.list_value)&&C.list_name!=="attribute_category");if(!G)await b.mutateAsync({list_name:t(A.list_name),list_value:t(A.list_value),display_label:t(A.display_label)||void 0,display_order:Number(A.display_order)||0,is_active:y(A.is_active)}),n++;else{const C=[];t(A.display_label)!==(G.display_label||"")&&C.push("x"),Number(A.display_order)!==G.display_order&&C.push("x"),y(A.is_active)!==G.is_active&&C.push("x"),C.length&&(await I.mutateAsync({id:G.id,updates:{display_label:t(A.display_label)||void 0,display_order:Number(A.display_order)||0,is_active:y(A.is_active)}}),R++)}}const Z=M(S,"Categories");for(const A of Z){const G=q.find(C=>C.list_value===t(A.list_value));if(!G)await b.mutateAsync({list_name:"attribute_category",list_value:t(A.list_value),display_label:t(A.display_label)||t(A.list_value),display_order:Number(A.display_order)||0,is_active:y(A.is_active),metadata:{double_width:y(A.double_width)}}),n++;else{const C=G.metadata,$=[];t(A.display_label)!==(G.display_label||"")&&$.push("x"),Number(A.display_order)!==G.display_order&&$.push("x"),y(A.is_active)!==G.is_active&&$.push("x"),y(A.double_width)!==((C==null?void 0:C.double_width)===!0)&&$.push("x"),$.length&&(await I.mutateAsync({id:G.id,updates:{display_label:t(A.display_label)||t(A.list_value),display_order:Number(A.display_order)||0,is_active:y(A.is_active),metadata:{...C||{},double_width:y(A.double_width)}}}),R++)}}L.success(`Import complete: ${n} added, ${R} updated`),w(!1),F(null),m([])}catch(a){L.error(a.message||"Import failed")}finally{V(!1)}},r=d.filter(n=>n.type==="add"||n.type==="update"),j=d.filter(n=>n.type==="skip");return e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs(N,{variant:"outline",size:"sm",onClick:p,className:"gap-2",children:[e.jsx(ls,{className:"h-4 w-4"}),"Export Data Model"]}),e.jsxs(N,{variant:"outline",size:"sm",onClick:()=>{var n;return(n=T.current)==null?void 0:n.click()},className:"gap-2",children:[e.jsx(js,{className:"h-4 w-4"}),"Import Data Model"]}),e.jsx("input",{ref:T,type:"file",accept:".xlsx,.xls",className:"hidden",onChange:h})]}),e.jsx(Ee,{open:o,onOpenChange:w,children:e.jsxs(Pe,{className:"",children:[e.jsxs(ze,{children:[e.jsx(Me,{children:"Import Data Model Changes"}),e.jsx(rt,{children:"Review changes from the Excel file. Deleti
26ons and attribute name changes are not allowed."})]}),e.jsx(na,{className:"max-h-[400px]",children:e.jsxs("div",{className:"space-y-3 pr-4",children:[r.length>0&&e.jsxs("div",{className:"space-y-2",children:[e.jsx("h4",{className:"text-sm font-medium text-foreground",children:"Changes to apply"}),r.map((n,R)=>e.jsxs("div",{className:"flex items-start gap-2 text-sm p-2 rounded-md bg-muted/50",children:[n.type==="add"?e.jsx(pa,{className:"h-4 w-4 text-green-500 mt-0.5 shrink-0"}):e.jsx(ma,{className:"h-4 w-4 text-blue-500 mt-0.5 shrink-0"}),e.jsxs("div",{children:[e.jsx("span",{className:"font-mono text-xs",children:n.name}),e.jsx(se,{variant:"outline",className:"ml-2 text-xs",children:n.sheet}),e.jsx(se,{variant:n.type==="add"?"default":"secondary",className:"ml-1 text-xs",children:n.type==="add"?"New":"Update"}),e.jsx("p",{className:"text-muted-foreground text-xs mt-0.5",children:n.details})]})]},R))]}),j.length>0&&e.jsxs("div",{className:"space-y-2",children:[e.jsx("h4",{className:"text-sm font-medium text-muted-foreground",children:"Skipped"}),j.map((n,R)=>e.jsxs("div",{className:"flex items-start gap-2 text-sm p-2 rounded-md bg-muted/30 opacity-60",children:[e.jsx(ha,{className:"h-4 w-4 text-muted-foreground mt-0.5 shrink-0"}),e.jsxs("div",{children:[e.jsx("span",{className:"font-mono text-xs",children:n.name}),e.jsx("p",{className:"text-muted-foreground text-xs mt-0.5",children:n.details})]})]},R))]}),d.length===0&&e.jsx("p",{className:"text-muted-foreground text-sm text-center py-4",children:"No changes detected â the file matches the current data model."})]})}),e.jsxs(qe,{children:[e.jsx(N,{variant:"outline",onClick:()=>w(!1),children:"Cancel"}),e.jsx(N,{onClick:x,disabled:r.length===0||P,children:P?"Importing...":`Apply ${r.length} change${r.length!==1?"s":""}`})]})]})})]})},Qt=[{value:"required_field",label:"Required Field"},{value:"min_length",label:"Minimum Length"},{value:"max_length",label:"Maximum Length"},{value:"regex",label:"Regex Pattern"},{value:"ai_rule",label:"AI-Powered Rule"}],rr=[{value:"product",label:"Product"},{value:"variant",label:"Variant"}],ir=[{value:"error",label:"Error (blocks publish)"},{value:"warning",label:"Warning"}],Ht=[{value:"_images",label:"Images (product has images)"},{value:"_variants",label:"Variants (product has variants)"},{value:"_translations",label:"Translations (all locales complete)"}],nr={name:"",description:"",rule_type:"required_field",applies_to:"product",target_field:"",rule_config:{},ai_prompt:"",severity:"warning",is_active:!0};function lr(){var q,y;const{currentOrg:s}=Se(),l=s==null?void 0:s.id,_=Ge(),[i,g]=c.useState(null),[f,b]=c.useState(!1),{data:I,isLoading:T}=je({queryKey:["validation-rules",l],queryFn:async()=>{if(!l)return[];const{data:t,error:p}=await U.from("validation_rules").select("*").eq("org_id",l).order("created_at",{ascending:!0});if(p)throw p;return t??[]},enabled:!!l}),{data:o}=je({queryKey:["attribute-names",l],queryFn:async()=>{if(!l)return[];const{data:t,error:p}=await U.rpc("pim_get_schema",{p_org_id:l,p_repository_key:"product"}).select("attribute_name, display_label").eq("org_id",l).eq("is_active",!0).order("attribute_name");if(p)throw p;return(t==null?void 0:t.map(D=>({...D,label:D.display_label})))??[]},enabled:!!l}),w=ht({mutationFn:async t=>{if(!l)throw new Error("No org");const p={org_id:l,name:t.name,description:t.description||null,rule_type:t.rule_type,applies_to:t.applies_to,target_field:t.target_field||null,rule_config:t.rule_config||{},ai_prompt:t.rule_type==="ai_rule"?t.ai_prompt:null,severity:t.severity,is_active:t.is_active??!0};if(t.id){const{error:D}=await U.from("validation_rules").update(p).eq("id",t.id);if(D)throw D}else{const{error:D}=await U.from("validation_rules").insert(p);if(D)throw D}},onSuccess:()=>{_.invalidateQueries({queryKey:["validation-rules"]}),g(null),b(!1),L.success("Validation rule saved")},onError:t=>{L.error(`Failed to save: ${t.message}`)}}),d=ht({mutationFn:async t=>{const{error:p}=await U.from("validation_rules").delete().eq("id",t);if(p)throw p},onSuccess:()=>{_.invalidateQueries({queryKey:["validation-rules"]}),L.success("Rule deleted")},onError:t=>{L.error(`Failed to delete: ${t.message}`)}}),m=ht({mutationFn:async({id:t,is_active:p})=>{const{error:D}=await U.from("validation_rules").update({is_active:p}).eq("id",t);if(D)throw D},onSuccess:()=>
26{_.invalidateQueries({queryKey:["validation-rules"]})}}),S=()=>{g({...nr}),b(!0)},F=t=>{g({...t}),b(!1)},P=t=>{var p;return((p=Qt.find(D=>D.value===t))==null?void 0:p.label)??t},V=t=>{if(!t)return"â";const p=Ht.find(h=>h.value===t);if(p)return p.label;const D=o==null?void 0:o.find(h=>h.attribute_name===t);return(D==null?void 0:D.label)||t};return T?e.jsxs("div",{className:"flex items-center justify-center py-12 text-muted-foreground",children:[e.jsx(Ze,{className:"h-4 w-4 animate-spin mr-2"})," Loading rulesâ¦"]}):e.jsxs("div",{className:"space-y-4",children:[e.jsxs(me,{className:"border-border/50 bg-card/50",children:[e.jsxs(Be,{className:"flex flex-row items-center justify-between pb-4",children:[e.jsxs("div",{children:[e.jsxs(Ue,{className:"text-lg flex items-center gap-2",children:[e.jsx(ga,{className:"h-5 w-5 text-primary"}),"Validation Rules"]}),e.jsx(at,{children:"Rules that agents use to validate product data before publishing. AI-powered rules use credits."})]}),e.jsxs(N,{onClick:S,size:"sm",className:"gap-1.5",children:[e.jsx(Ne,{className:"h-4 w-4"})," Add Rule"]})]}),e.jsx(Te,{children:I!=null&&I.length?e.jsxs(ft,{children:[e.jsx(_t,{children:e.jsxs(Oe,{children:[e.jsx(_e,{children:"Name"}),e.jsx(_e,{children:"Type"}),e.jsx(_e,{children:"Field"}),e.jsx(_e,{children:"Severity"}),e.jsx(_e,{className:"text-center",children:"Active"}),e.jsx(_e,{className:"text-right",children:"Actions"})]})}),e.jsx(yt,{children:I.map(t=>e.jsxs(Oe,{children:[e.jsxs(ee,{className:"font-medium",children:[e.jsxs("div",{className:"flex items-center gap-1.5",children:[t.rule_type==="ai_rule"&&e.jsx(gt,{className:"h-3.5 w-3.5 text-amber-500 flex-shrink-0"}),t.name]}),t.description&&e.jsx("div",{className:"text-xs text-muted-foreground mt-0.5 max-w-[250px] truncate",children:t.description})]}),e.jsx(ee,{children:e.jsx(se,{variant:"outline",className:"text-xs",children:P(t.rule_type)})}),e.jsx(ee,{className:"text-sm text-muted-foreground",children:V(t.target_field)}),e.jsx(ee,{children:e.jsx(se,{variant:t.severity==="error"?"destructive":"secondary",className:"text-xs",children:t.severity})}),e.jsx(ee,{className:"text-center",children:e.jsx(Ce,{checked:t.is_active,onCheckedChange:p=>m.mutate({id:t.id,is_active:p})})}),e.jsx(ee,{className:"text-right",children:e.jsxs("div",{className:"flex items-center justify-end gap-1",children:[e.jsx(N,{variant:"ghost",size:"icon",className:"h-8 w-8",onClick:()=>F(t),children:e.jsx(We,{className:"h-3.5 w-3.5"})}),e.jsx(N,{variant:"ghost",size:"icon",className:"h-8 w-8 text-destructive hover:text-destructive",onClick:()=>{confirm(`Delete rule "${t.name}"?`)&&d.mutate(t.id)},children:e.jsx($e,{className:"h-3.5 w-3.5"})})]})})]},t.id))})]}):e.jsx("div",{className:"text-center py-8 text-muted-foreground text-sm",children:"No validation rules configured. Add rules to define quality standards for your catalog."})})]}),e.jsx(Ee,{open:!!i,onOpenChange:t=>{t||(g(null),b(!1))},children:e.jsxs(Pe,{className:"sm:max-w-[520px]",children:[e.jsx(ze,{children:e.jsx(Me,{children:f?"Create Validation Rule":"Edit Validation Rule"})}),i&&e.jsxs("div",{className:"space-y-4 py-2",children:[e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(W,{children:"Name"}),e.jsx(te,{value:i.name||"",onChange:t=>g({...i,name:t.target.value}),placeholder:"e.g. Product Name is required"})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(W,{children:"Description (optional)"}),e.jsx(te,{value:i.description||"",onChange:t=>g({...i,description:t.target.value}),placeholder:"Explain what this rule checks"})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(W,{children:"Rule Type"}),e.jsxs(re,{value:i.rule_type,onValueChange:t=>g({...i,rule_type:t}),children:[e.jsx(ie,{children:e.jsx(ne,{})}),e.jsx(le,{children:Qt.map(t=>e.jsx(J,{value:t.value,children:t.label},t.value))})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(W,{children:"Applies To"}),e.jsxs(re,{value:i.applies_to,onValueChange:t=>g({...i,applies_to:t}),children:[e.jsx(ie,{children:e.jsx(ne,{})}),e.jsx(le,{children:rr.map(t=>e.jsx(J,{value:t.value,children:t.label},t.value))})]})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(W,{children:"Target Field"}),e.jsxs(re,{value:i.target_field||"",onValueChange:t=>g({...i,target_field:t}),children:[e.jsx(ie,{children:e.jsx(ne,{placeholder:"Select fieldâ¦"})}),e.jsxs(le,{children:[Ht.map(t=>e.jsx(J,{value:t.value,children:t.label},t.value)),o==null?void 0:o.map(t=>e.jsx(J,{value:t.attribute_name,children:t.label||t.attribute_name},t.attribute_name))]})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(W,{children:"Severity"}),e.jsxs(re,{value:i.severity,onValueChange:t=>g({...i,severity:t}),children:[e.jsx(ie,{children:e.jsx(ne,{})}),e.jsx(le,{children:ir.map(t=>e.jsx(J,{value:t.value,children:t.label},t.value))})]})]}),(i.rule_type==="min_length"||i.rule_type==="max_length")&&e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(W,{children:i.rule_type==="min_length"?"Minimum Characters":"Maximum Characters"}),e.jsx(te,{type:"number",value:((q=i.rule_config)==null?void 0:q[i.rule_type==="min_length"?"min_length":"max_length"])||"",onChange:t=>{const p=i.rule_type==="min_length"?"min_length":"max_length";g({...i,rule_config:{...i.rule_config,[p]:parseInt(t.target.value)||0}})},placeholder:"e.g. 50"})]}),i.rule_type==="regex"&&e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(W,{children:"Regex Pattern"}),e.jsx(te,{value:((y=i.rule_config)==null?void 0:y.pattern)||"",onChange:t=>g({...i,rule_config:{...i.rule_config,pattern:t.target.value}}),placeholder:"e.g. ^[A-Z].*"})]}),i.rule_type==="ai_rule"&&e.jsxs("div",{className:"space-y-1.5",children:[e.jsxs(W,{className:"flex items-center gap-1.5",children:[e.jsx(gt,{className:"h-3.5 w-3.5 text-amber-500"}),"AI Validation Prompt"]}),e.jsx(Lt,{value:i.ai_prompt||"",onChange:t=>g({...i,ai_prompt:t.target.value}),placeholder:"Describe what the AI should check, e.g. 'Description should be professional, not contain placeholder text, and accurately describe the product'",rows:3}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"AI rules consume 2 credits per product validated."})]})]}),e.jsxs(qe,{children:[e.jsx(N,{variant:"outline",onClick:()=>{g(null),b(!1)},children:"Cancel"}),e.jsxs(N,{onClick:()=>i&&w.mutate(i),disabled:!(i!=null&&i.name)||w.isPending,children:[w.isPending&&e.jsx(Ze,{className:"h-4 w-4 animate-spin mr-1.5"}),f?"Create":"Save"]})]})]})})]})}const Wt={pending:"bg-muted text-muted-foreground",processing:"bg-blue-500/15 text-blue-700 dark:text-blue-400",complete:"bg-green-500/15 text-green-700 dark:text-green-400",failed:"bg-destructive/15 text-destructive"};function or(){const{currentOrg:s}=Se(),l=s==null?void 0:s.id,[_,i]=c.useState([]),[g,f]=c.useState(!0),[b,I]=c.useState(!1),[T,o]=c.useState(""),[w,d]=c.useState(!1),[m,S]=c.useState(null),[F,P]=c.useState(!1),[V,q]=c.useState([]),[y,t]=c.useState(!0);c.useEffect(()=>{if(!l)return;(async()=>{f(!0);const{data:X}=await U.from("erp_api_keys").select("id, key_prefix, label, last_used_at, revoked_at, created_at").eq("org_id",l).order("created_at",{ascending:!1});i(X||[]),f(!1)})()},[l]),c.useEffect(()=>{if(!l)return;(async()=>{t(!0);const{data:X}=await U.from("erp_import_jobs").select("id, created_at, source, file_path, status, rows_ok, rows_error").eq("org_id",l).order("created_at",{ascending:!1}).limit(20);q(X||[]),t(!1)})()},[l]);const p=async()=>
26{if(l){d(!0);try{const{data:{session:E}}=await U.auth.getSession(),X=await U.functions.invoke("erp-generate-key",{body:{org_id:l,label:T||"API key"}});if(X.error)throw X.error;const x=X.data;S(x),i(r=>[{id:x.id,key_prefix:x.key_prefix,label:x.label,last_used_at:null,revoked_at:null,created_at:x.created_at},...r]),I(!1),o(""),L.success("API key generated")}catch(E){L.error((E==null?void 0:E.message)||"Failed to generate key")}finally{d(!1)}}},D=async E=>{const{error:X}=await U.from("erp_api_keys").update({revoked_at:new Date().toISOString()}).eq("id",E);if(X){L.error("Failed to revoke key");return}i(x=>x.map(r=>r.id===E?{...r,revoked_at:new Date().toISOString()}:r)),L.success("Key revoked")},h=async E=>{await navigator.clipboard.writeText(E),P(!0),setTimeout(()=>P(!1),2e3)},M=E=>E?new Date(E).toLocaleDateString():"â",Q=E=>E.split("/").pop()||E;return e.jsxs("div",{className:"space-y-8 max-w-4xl",children:[e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("h1",{className:"text-2xl font-bold tracking-tight",children:"ERP Import"}),e.jsx(St,{text:"Generate API keys for your ERP or cron jobs to push CSV/XLSX files directly to SKUuz without logging in. Requires API Upload entitlement.",guide:"admin",section:14,userGuide:{section:10,label:"User: Import Hub"}})]}),e.jsx("p",{className:"text-muted-foreground mt-1",children:"Manage API keys and view automated import history."})]}),e.jsxs(me,{children:[e.jsxs(Be,{children:[e.jsxs(Ue,{className:"flex items-center gap-2",children:[e.jsx(Aa,{className:"h-5 w-5"}),"API keys for automated uploads"]}),e.jsx(at,{children:"Give your ERP or cron job an API key to push files directly to SKUuz without logging in."})]}),e.jsxs(Te,{className:"space-y-4",children:[m&&e.jsxs("div",{className:"rounded-lg border border-primary/30 bg-primary/5 p-4 space-y-2",children:[e.jsx("p",{className:"text-sm font-medium text-primary",children:"Copy this key now â it won't be shown again"}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("code",{className:"flex-1 text-sm bg-muted px-3 py-2 rounded-md font-mono break-all",children:m.key}),e.jsx(N,{size:"icon",variant:"outline",onClick:()=>h(m.key),children:F?e.jsx(Nt,{className:"h-4 w-4"}):e.jsx(fa,{className:"h-4 w-4"})})]}),e.jsx(N,{variant:"ghost",size:"sm",onClick:()=>S(null),className:"mt-1",children:"Dismiss"})]}),g?e.jsx("p",{className:"text-sm text-muted-foreground",children:"Loadingâ¦"}):_.length===0?e.jsx("p",{className:"text-sm text-muted-foreground",children:"No API keys yet."}):e.jsxs(ft,{children:[e.jsx(_t,{children:e.jsxs(Oe,{children:[e.jsx(_e,{children:"Label"}),e.jsx(_e,{children:"Key"}),e.jsx(_e,{children:"Last Used"}),e.jsx(_e,{children:"Created"}),e.jsx(_e,{className:"w-[100px]"})]})}),e.jsx(yt,{children:_.map(E=>e.jsxs(Oe,{className:E.revoked_at?"opacity-50":"",children:[e.jsxs(ee,{className:"font-medium",children:[E.label,E.revoked_at&&e.jsx(se,{variant:"destructive",className:"ml-2 text-[10px]",children:"Revoked"})]}),e.jsxs(ee,{className:"font-mono text-sm",children:[E.key_prefix,"â¢â¢â¢â¢â¢â¢â¢â¢"]}),e.jsx(ee,{children:M(E.last_used_at)}),e.jsx(ee,{children:M(E.created_at)}),e.jsx(ee,{children:!E.revoked_at&&e.jsxs(N,{variant:"ghost",size:"sm",onClick:()=>D(E.id),className:"text-destructive hover:text-destructive",children:[e.jsx(os,{className:"h-3.5 w-3.5 mr-1"}),"Revoke"]})})]},E.id))})]}),b?e.jsxs("div",{className:"flex items-end gap-3",children:[e.jsxs("div",{className:"flex-1 space-y-1",children:[e.jsx("label",{className:"text-sm font-medium",children:"Label"}),e.jsx(te,{placeholder:"e.g. API Key Here",value:T,onChange:E=>o(E.target.value)})]}),e.jsx(N,{onClick:p,disabled:w,children:w?"Generatingâ¦":"Generate"}),e.jsx(N,{variant:"outline",onClick:()=>I(!1),children:"Cancel"})]}):e.jsxs(N,{variant:"outline",onClick:()=>I(!0),children:[e.jsx(Ne,{className:"h-4 w-4 mr-2"}),"Generate new key"]})]})]}),e.jsxs(me,{children:[e.jsx(Be,{children:e.jsxs(Ue,{className:"flex items-center gap-2",children:[e.jsx(_a,{className:"h-5 w-5"}),"Recent imports"]})}),e.jsx(Te,{children:y?e.jsx("p",{className:"text-sm text-muted-foreground",children:"Loadingâ¦"}):V.length===0?e.jsx("p",{className:"text-sm text-muted-foreground",children:"No imports yet."}):e.jsxs(ft,{children:[e.jsx(_t,{children:e.jsxs(Oe,{children:[e.jsx(_e,{children:"Date"}),e.jsx(_e,{children:"Source"}),e.jsx(_e,{children:"File"}),e.jsx(_e,{children:"Status"}),e.jsx(_e,{children:"Rows OK"}),e.jsx(_e,{children:"Rows Error"})]})}),e.jsx(yt,{children:V.map(E=>e.jsxs(Oe,{children:[e.jsx(ee,{children:M(E.created_at)}),e.jsx(ee,{children:e.jsx(se,{variant:"secondary",children:E.source==="api"?"API":"Manual"})}),e.jsx(ee,{className:"font-mono text-xs max-w-[200px] truncate",children:Q(E.file_path)}),e.jsx(ee,{children:e.jsx(se,{className:Wt[E.status]||Wt.pending,children:E.status})}),e.jsx(ee,{children:E.rows_ok??"â"}),e.jsx(ee,{children:E.rows_error??"â"})]},E.id))})]})})]})]})}function cr(){const{currentOrg:s}=Se(),l=s==null?void 0:s.id;return je({queryKey:["settings-annotations",l],queryFn:async()=>
26{if(!l)throw new Error("No organization");const{data:_,error:i}=await U.rpc("get_settings_annotations",{p_org_id:l});if(i)throw i;return _},enabled:!!l,staleTime:15e3})}function dr(s){const{currentOrg:l}=Se(),_=l==null?void 0:l.id;return je({queryKey:["model-changelog",_,s],queryFn:async()=>{if(!_)throw new Error("No organization");const{data:i,error:g}=await U.rpc("pim_get_model_changelog",{p_org_id:_,p_entity_type:null,p_entity_id:null,p_limit:50,p_offset:0});if(g)throw g;return i},enabled:!!_,staleTime:1e4})}const Di=()=>{var n,R;const[s,l]=c.useState("global-attrs"),[_,i]=c.useState("lists"),[g,f]=c.useState("product"),[b,I]=c.useState(!1),{repositories:T}=ts(),[o,w]=hs(),d=["general","data-model","ai-content","integrations","validation-rules","agents","history"],m=(()=>{const a=o.get("tab");return a&&d.includes(a)?a:"general"})(),[S,F]=c.useState(m),P=c.useCallback(a=>{F(a),w({tab:a},{replace:!0})},[w]),[V,q]=c.useState("prompts"),[y,t]=c.useState("erp-import"),p=c.useRef(null),[D,h]=c.useState({canSave:!1,isSaving:!1}),{currentOrg:M}=Se(),{hasPermission:Q}=Ns(),E=Q("record.undelete"),X=c.useCallback(a=>{h(a)},[]);xs();const{pendingRequests:x}=Zt();xa();const{data:r}=cr(),{data:j}=dr();return e.jsxs(e.Fragment,{children:[e.jsxs(ws,{children:[e.jsx("title",{children:"Settings | Product Catalog Manager | SKUuz"}),e.jsx("meta",{name:"description",content:"Configure catalog manager settings"})]}),e.jsxs("div",{className:"h-full flex flex-col p-6 lg:p-8 overflow-auto",children:[e.jsx("div",{className:"flex items-center gap-4 mb-6",children:e.jsxs("div",{className:"flex-1",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("h1",{className:"text-2xl font-bold text-foreground",children:"Control Panel"}),e.jsx(St,{text:"Configure your data model, AI prompts, publish channels, and organization settings. Changes here affect all users.",guide:"admin",section:0,userGuide:{section:0,label:"User: Getting Started"}})]}),e.jsx("p",{className:"text-muted-foreground text-sm",children:"Configure your catalog settings and preferences"})]})}),e.jsxs(Cs,{value:S,onValueChange:P,className:"space-y-4",children:[e.jsxs(Ss,{children:[e.jsxs(Qe,{value:"general",className:"gap-2",children:[e.jsx(Mt,{className:"h-4 w-4"}),"General"]}),e.jsxs(Qe,{value:"data-model",className:"gap-2",children:[e.jsx(ks,{className:"h-4 w-4"}),"Data Model"]}),e.jsxs(Qe,{value:"ai-content",className:"gap-2",children:[e.jsx(gt,{className:"h-4 w-4"}),"AI & Content"]}),e.jsxs(Qe,{value:"integrations",className:"gap-2",children:[e.jsx(ja,{className:"h-4 w-4"}),"Integrations"]}),e.jsxs(Qe,{value:"validation-rules",className:"gap-2",children:[e.jsx(Vt,{className:"h-4 w-4"}),"Validation Rules"]}),e.jsxs(Qe,{value:"agents",className:"gap-2",children:[e.jsx(as,{className:"h-4 w-4"}),"Agents"]}),e.jsxs(Qe,{value:"history",className:"gap-2",children:[e.jsx(Kt,{className:"h-4 w-4"}),"History"]}),E&&e.jsxs(Qe,{value:"soft-deleted",className:"gap-2",children:[e.jsx($e,{className:"h-4 w-4"}),"Soft-Deleted Records"]})]}),r&&e.jsxs("div",{className:"flex flex-wrap gap-x-5 gap-y-1 text-xs text-muted-foreground -mt-2 mb-2",children:[S==="general"&&e.jsxs("span",{children:["Publish interval: ",e.jsx("strong",{className:"text-foreground",children:r.publish_interval?`${Math.round(Number(r.publish_interval)/60)} min`:"Not set"})]}),S==="data-model"&&e.jsxs(e.Fragment,{children:[e.jsxs("span",{children:[e.jsx("strong",{className:"text-foreground",children:r.attribute_count})," attributes · ",e.jsx("strong",{className:"text-foreground",children:r.field_group_count})," groups · ",e.jsx("strong",{className:"text-foreground",children:r.category_count})," categories"]}),r.model_changes_this_week>0&&e.jsxs("span",{children:[r.model_changes_this_week," change",r.model_changes_this_week!==1?"s":""," this week"]})]}),S==="ai-content"&&e.jsx(e.Fragment,{children:e.jsxs("span",{children:["BrandGuard: ",e.jsxs("strong",{className:"text-foreground",children:[r.brandguard_terms," terms"]})]})}),S==="validation-rules"&&e.jsxs("span",{children:[e.jsx("strong",{className:"text-foreground",children:r.active_rules})," active of ",r.total_rules," rules"]}),S==="agents"&&e.jsxs(e.Fragment,{children:[e.jsxs("span",{children:[e.jsx("strong",{className:"text-foreground",children:r.active_agents})," active of ",r.total_agents," agents"]}),r.last_agent_run&&e.jsxs("span",{children:["Last run: ",new Date(r.last_agent_run).toLocaleDateString()]})]}),S==="history"&&j&&e.jsxs("span",{children:[e.jsx("strong",{className:"text-foreground",children:j.total})," changes recorded"]})]}),e.jsxs(He,{value:"general",className:"space-y-6",children:[e.jsx(tr,{}),e.jsxs(me,{className:"border-border/50 bg-card/50",children:[e.jsxs(Be,{children:[e.jsx(Ue,{children:"Command Center Agent"}),e.jsx(at,{children:"Personalize your CC Agent â change its name and avatar"})]}),e.jsx(Te,{children:e.jsx(ya,{variant:"full"})})]}),e.jsxs(me,{className:"border-border/50 bg-card/50",children:[e.jsxs(Be,{children:[e.jsx(Ue,{children:"Data Model Export"}),e.jsx(at,{children:"Download your complete data model as an Excel spreadsheet. Edit it and upload back to CC to apply changes."})]}),e.jsx(Te,{className:"flex gap-3",children:e.jsxs(N,{variant:"outline",size:"sm",className:"gap-2",onClick:()=>{M!=null&&M.id&&va(M.id,M.name)},children:[e.jsx(ls,{className:"h-4 w-4"}),"Export to Excel"]})})]})]}),e.jsxs(He,{value:"ai-content",className:"space-y-4",children:[e.jsxs("div",{className:"flex gap-2",children:[e.jsxs(N,{variant:V==="prompts"?"default":"outline",size:"sm",onClick:()=>q("prompts"),className:"gap-2",children:[e.jsx(gt,{className:"h-4 w-4"}),"AI Field Prompts"]}),e.jsxs(N,{variant:V==="brandguard"?"default":"outline",size:"sm",onClick:()=>q("brandguard"),className:"gap-2",children:[e.jsx(Yt,{className:"h-4 w-4"}),"BrandGuardâ¢"]})]}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:[V==="prompts"&&"Configure which attributes are generated by AI and customize their prompts, tone, and content type.",V==="brandguard"&&"Define brand terms, product line names, and industry vocabulary to protect during AI content generation and translation."]}),V==="prompts"&&e.jsx(ms,{ref:p,onStateChange:X}),V==="brandguard"&&e.jsx(ba,{embedded:!0})]}),e.jsxs(He,{value:"data-model",className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center gap-4 flex-wrap",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"text-xs font-semibold uppercase tracking-wider text-muted-foreground",children:"Entity Type"}),e.jsxs(re,{value:g,onValueChange:a=>f(a),children:[e.jsx(ie,{className:"w-44 h-9",children:e.jsx(ne,{})}),e.jsx(le,{children:T.map(a=>e.jsx(J,{value:a.key,children:a.label},a.key))})]}),e.jsx(N,{variant:"ghost",size:"icon",className:"h-9 w-9 text-muted-foreground hover:text-foreground",title:"Entity settings",onClick:()=>I(!0),children:e.jsx(Mt,{className:"h-4 w-4"})})]}),e.jsx("div",{className:"flex-1"}),e.jsx(ar,{})]}),(M==null?void 0:M.id)&&e.jsx(Ga,{open:b,onOpenChange:I,orgId:M.id,repoKey:g,repoLabel:((n=T.find(a=>a.key===g))==null?void 0:n.label)??g,currentDisplayNameAttributeId:((R=T.find(a=>a.key===g))==null?void 0:R.display_name_attribute_id)??null}),e.jsxs("div",{className:"flex gap-2 flex-wrap",children:[e.jsxs(N,{variant:s==="global-attrs"?"default":"outline",size:"sm",onClick:()=>l("global-attrs"),className:"gap-2",children:[e.jsx(Ot,{className:"h-4 w-4"}),"Global Attributes"]}
26),e.jsxs(N,{variant:s==="categories"?"default":"outline",size:"sm",onClick:()=>l("categories"),className:"gap-2",children:[e.jsx(qt,{className:"h-4 w-4"}),"Categories"]}),e.jsxs(N,{variant:s==="relationships"?"default":"outline",size:"sm",onClick:()=>l("relationships"),className:"gap-2",children:[e.jsx(Na,{className:"h-4 w-4"}),"Relationships"]}),e.jsxs(N,{variant:s==="lists"?"default":"outline",size:"sm",onClick:()=>{l("lists"),i("lists")},className:"gap-2",children:[e.jsx(wa,{className:"h-4 w-4"}),"Lists",x.length>0&&e.jsx(se,{variant:"destructive",className:"ml-1 h-5 min-w-[20px] px-1 cursor-pointer",onClick:a=>{a.stopPropagation(),l("lists"),i("value-requests")},children:x.length})]}),e.jsxs(N,{variant:s==="layout"?"default":"outline",size:"sm",onClick:()=>l("layout"),className:"gap-2",children:[e.jsx(qt,{className:"h-4 w-4"}),"Layout"]})]}),s==="global-attrs"&&e.jsx(me,{className:"border-border/50 bg-card/50 overflow-hidden",children:e.jsx(Ta,{repositoryKey:g})}),s==="categories"&&e.jsx(Ua,{}),s==="relationships"&&e.jsx(me,{className:"border-border/50 bg-card/50 overflow-hidden",children:e.jsx(Oa,{repositoryKey:g})}),s==="lists"&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"flex gap-2",children:[e.jsx(N,{variant:_==="lists"?"secondary":"ghost",size:"sm",onClick:()=>i("lists"),className:"text-xs",children:"List Values"}),e.jsxs(N,{variant:_==="value-requests"?"secondary":"ghost",size:"sm",onClick:()=>i("value-requests"),className:he("text-xs",x.length>0&&_!=="value-requests"&&"text-destructive"),children:[e.jsx(Vt,{className:"h-3 w-3 mr-1"}),"Value Requests",x.length>0&&e.jsx(se,{variant:"destructive",className:"ml-1 h-5 min-w-[20px] px-1",children:x.length})]})]}),_==="lists"&&e.jsxs(me,{className:"border-border/50 bg-card/50",children:[e.jsxs(Be,{children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Ue,{children:"Lists"}),e.jsx(St,{text:"Define the dropdown options available for select-type attributes (e.g. weight units, inventory policies).",guide:"admin",section:4,userGuide:{section:4,label:"User: Product Detail"}})]}),e.jsx(at,{children:"Manage dropdown and selection list values"})]}),e.jsx(Te,{children:e.jsx(Ya,{})})]}),_==="value-requests"&&e.jsx(me,{className:"border-border/50 bg-card/50",children:e.jsx(Te,{className:"pt-6",children:e.jsx(Wa,{})})})]}),s==="layout"&&e.jsx(me,{className:"border-border/50 bg-card/50 overflow-hidden",children:e.jsx(Ds,{})})]}),e.jsxs(He,{value:"integrations",className:"space-y-4",children:[e.jsxs("div",{className:"flex gap-2",children:[e.jsxs(N,{variant:y==="erp-import"?"default":"outline",size:"sm",onClick:()=>t("erp-import"),className:"gap-2",children:[e.jsx(Ot,{className:"h-4 w-4"}),"ERP Import"]}),e.jsxs(N,{variant:y==="channel-log"?"default":"outline",size:"sm",onClick:()=>t("channel-log"),className:"gap-2",children:[e.jsx(ka,{className:"h-4 w-4"}),"Channel Log"]})]}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:[y==="erp-import"&&"Manage API keys for automated imports and view recent import history.",y==="channel-log"&&"Track product changes within publish hierarchy nodes."]}),y==="erp-import"&&e.jsx(or,{}),y==="channel-log"&&e.jsx(me,{className:"border-border/50 bg-card/50",children:e.jsx(Te,{className:"pt-6",children:e.jsx(sr,{})})})]}),e.jsx(He,{value:"validation-rules",className:"space-y-6",children:e.jsx(lr,{})}),e.jsx(He,{value:"agents",children:e.jsx(me,{className:"border-border/50 bg-card/50 overflow-hidden",children:e.jsx(Ma,{})})}),e.jsxs(He,{value:"history",className:"space-y-4",children:[e.jsx("div",{className:"flex items-center justify-between",children:e.jsxs("div",{children:[e.jsx("h2",{className:"text-sm font-semibold text-foreground",children:"Change History"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Every change to your data model, settings, agents, and rules â with one-click revert."})]})}),j&&j.entries.length>0?e.jsx(me,{className:"border-border/50 bg-card/50 overflow-hidden",children:e.jsx("div",{className:"divide-y divide-border/50",children:j.entries.map(a=>e.jsxs("div",{className:"px-4 py-3 flex items-start gap-3 hover:bg-muted/20 transition-colors group",children:[e.jsx("div",{className:he("mt-1 h-2 w-2 rounded-full shrink-0",a.action==="create"&&"bg-success",a.action==="update"&&"bg-primary",a.action==="delete"&&"bg-destructive")}
26),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-0.5",children:[e.jsx("span",{className:"text-sm font-medium text-foreground",children:a.entity_label}),e.jsx(se,{variant:"outline",className:"text-[10px] px-1.5 py-0",children:a.entity_type.replace("_"," ")}),e.jsx(se,{variant:a.action==="delete"?"destructive":"secondary",className:"text-[10px] px-1.5 py-0",children:a.action})]}),a.field_name&&e.jsxs("p",{className:"text-xs text-muted-foreground",children:[e.jsx("span",{className:"font-medium",children:a.field_name}),a.old_value!=null&&e.jsxs(e.Fragment,{children:[e.jsx("span",{className:"mx-1",children:":"}),e.jsx("span",{className:"line-through text-destructive/70",children:String(a.old_value).slice(0,60)})]}),a.new_value!=null&&e.jsxs(e.Fragment,{children:[e.jsx("span",{className:"mx-1",children:"â"}),e.jsx("span",{className:"text-success",children:String(a.new_value).slice(0,60)})]})]}),e.jsxs("p",{className:"text-[10px] text-muted-foreground/60 mt-0.5",children:[new Date(a.changed_at).toLocaleString(),a.changed_by_name&&` · ${a.changed_by_name}`]})]}),a.action==="update"&&a.field_name&&e.jsxs(N,{size:"sm",variant:"ghost",className:"shrink-0 opacity-0 group-hover:opacity-100 transition-opacity text-xs gap-1",onClick:async()=>{const{data:k,error:Y}=await U.rpc("pim_revert_model_change",{p_changelog_id:a.id});if(Y){L.error(Y.message);return}const Z=k;Z.success?L.success(`Reverted ${a.field_name} on ${a.entity_label}`):L.error(Z.error||"Revert failed")},children:[e.jsx(ua,{className:"h-3 w-3"}),"Revert"]})]},a.id))})}):e.jsxs("div",{className:"text-center py-12 border-2 border-dashed border-border rounded-xl",children:[e.jsx(Kt,{className:"h-10 w-10 text-muted-foreground/30 mx-auto mb-3"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"No changes recorded yet."}),e.jsx("p",{className:"text-xs text-muted-foreground/60 mt-1",children:"Changes to attributes, validation rules, agent config, settings, and BrandGuard terms will appear here."})]})]}),E&&e.jsx(He,{value:"soft-deleted",className:"space-y-4",children:e.jsx($a,{})})]})]})]})};export{Di as default};
Line numbers count LF bytes from the start of the resource, as the search results do. Vendor segments are library code the classifier recognised; they are stored but not indexed. Bytes are shown as Latin1 characters, one per byte.