1import{j as e}from"./ui-vendor-CBbdTawN.js";import{r as t,i as s}from"./react-vendor-DQSFk_7t.js";import{b as a,N as r,s as o,a as n,c as i,X as l,u as d,ac as c,U as m,$ as p,Z as u,O as x}from"./index-DNEY-jN9.js";import{S as h}from"./search-CrbwOhvm.js";import{L as f}from"./loader-circle-BfESpXus.js";import{G as g,A as v}from"./globe-CasWFQRG.js";import{R as b}from"./refresh-cw-CXKaB8BA.js";import{C as y}from"./check-bGLc-vEg.js";import{F as j}from"./file-text-C4z4xXcw.js";import{E as w}from"./external-link-DU6lrNhI.js";import{U as N}from"./upload-Cg02cCm1.js";import{C as k}from"./circle-check-BQBZf-Xi.js";import{C as _}from"./circle-alert-C02fw8UP.js";import{C}from"./clock-aJQxKIS0.js";import{D as S,S as A,G as $}from"./scroll-text-DWQFIoUO.js";import{C as D}from"./calendar-9V2MJunA.js";import{M as E}from"./mail-CrtCbnBp.js";import{L as M}from"./link-2-ClQHNJ5v.js";import{S as F}from"./sparkles-Bnyn742X.js";import{S as R}from"./shield-alert-DjNPtYFf.js";import{_ as T}from"./supabase-NZ2Vt4Mp.js";import{F as q}from"./FreshnessBadge-6ano_gt9.js";import{B as I}from"./brain-DQ-8ElQ2.js";import{B as L}from"./book-open-BypW52Nk.js";import{A as U}from"./arrow-right-DdJtwgSW.js";import{A as O}from"./arrow-left-CdZc0h12.js";import"./chart-vendor-Dq0yAQdW.js";import"./form-vendor-CzIjS8Un.js"; 2/** 3 * @license lucide-react v0.363.0 - ISC 4 * 5 * This source code is licensed under the ISC license. 6 * See the LICENSE file in the root directory of this source tree. 7 */const P=a("CalendarClock",[["path",{d:"M21 7.5V6a2 2 0 0 0-2-2H5a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h3.5",key:"1osxxc"}],["path",{d:"M16 2v4",key:"4m81vk"}],["path",{d:"M8 2v4",key:"1cmpym"}],["path",{d:"M3 10h5",key:"r794hk"}],["path",{d:"M17.5 17.5 16 16.3V14",key:"akvzfd"}],["circle",{cx:"16",cy:"16",r:"6",key:"qoo3c4"}]]),H=a("Table",[["path",{d:"M12 3v18",key:"108xh3"}],["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",key:"afitv7"}],["path",{d:"M3 9h18",key:"1pudct"}],["path",{d:"M3 15h18",key:"5xshup"}]]),z=a("Webhook",[["path",{d:"M18 16.98h-5.99c-1.1 0-1.95.94-2.48 1.9A4 4 0 0 1 2 17c.01-.7.2-1.4.57-2",key:"q3hayz"}],["path",{d:"m6 17 3.13-5.78c.53-.97.1-2.18-.5-3.1a4 4 0 1 1 6.89-4.06",key:"1go1hn"}],["path",{d:"m12 6 3.13 5.73C15.66 12.7 16.9 13 18 13a4 4 0 0 1 0 8",key:"qlwsc0"}]]),B="https://n71-mission-worker.fly.dev",G={"dha.gov.ae":"DHA · Dubai Health Authority","damanhealth.ae":"Daman National Health Insurance","fcsc.gov.ae":"FCSC · Federal Statistics Centre","mohap.gov.ae":"MOHAP · Ministry of Health & Prevention","u.ae":"U.AE · Federal Government Portal","doh.gov.ae":"DOH · Department of Health Abu Dhabi","data.gov.ae":"data.gov.ae · Federal Open Data","seha.ae":"SEHA · Abu Dhabi Health Services","mof.gov.ae":"MoF · Ministry of Finance","ica.gov.ae":"ICP · Identity & Citizenship","moec.gov.ae":"MoEc · Ministry of Economy","tdra.gov.ae":"TDRA · Telecom & Digital Gov","moe.gov.ae":"MoE · Ministry of Education","ehs.ae":"EHS · Emirates Health Services","abudhabi.ae":"abudhabi.ae · AD Government","scad.gov.ae":"SCAD · Statistics Centre Abu Dhabi","dsc.gov.ae":"DSC · Dubai Statistics Centre","tamm.abudhabi":"TAMM · Abu Dhabi Services","dubaihealth.ae":"Dubai Health · DHCC"},W=Object.keys(G); 8/** 9 * @license lucide-react v0.363.0 - ISC 10 * 11 * This source code is licensed under the ISC license. 12 * See the LICENSE file in the root directory of this source tree. 13 */function J(){const{workspace:s}=r(),[a,d]=t.useState([]),[c,m]=t.useState(!0),[p,u]=t.useState(!1),[x,v]=t.useState(!1),[N,k]=t.useState(new Set),[_,C]=t.useState("all"),[S,A]=t.useState(null),$=t.useCallback(async()=>{var e;if(s){m(!0);try{const{data:t}=await o.auth.getSession(),s=null==(e=t.session)?void 0:e.access_token;if(!s)return void m(!1);const a=new URLSearchParams;a.set("limit","300"),"all"!==_&&a.set("source",_);const r=await fetch(`${B}/ministry/ingest/pending-review?${a}`,{headers:{Authorization:`Bearer ${s}`}}),i=await r.json();if(!r.ok)return void n.error(`Failed to load pending review: ${i.error??r.statusText}`);d(Array.isArray(i.items)?i.items:[]),k(new Set)}catch(t){n.error(`Network error: ${t instanceof Error?t.message:String(t)}`)}finally{m(!1)}}},[s,_]);t.useEffect(()=>{$()},[$]);const D=t.useMemo(()=>{const e={};for(const t of a){const s=t.source??"unknown";e[s]=(e[s]??0)+1}return e},[a]),E=async e=>{var t;u(!0),A(null);try{const{data:s}=await o.auth.getSession(),a=null==(t=s.session)?void 0:t.access_token;if(!a)return n.error("Sign-in required"),void u(!1);n.info("Discovery running â this can take several minutes per source.",{duration:8e3});const r=await fetch(`${B}
13/ministry/ingest/discover`,{method:"POST",headers:{Authorization:`Bearer ${a}`,"Content-Type":"application/json"},body:JSON.stringify(e&&e.length>0?{sources:e}:{})}),i=await r.json();if(!r.ok)return void n.error(`Discovery failed: ${i.error??r.statusText}`);const l=i.result;A({staged:l.total_staged,duplicates:l.total_duplicates,errors:l.total_errors,by_source:(l.by_source??[]).map(e=>({source:String(e.source),staged:Number(e.staged??0),duplicates:Number(e.duplicates??0),errors:Number(e.errors??0)}))}),n.success(`Discovery complete · ${l.total_staged} new docs staged · ${l.total_duplicates} dupes · ${l.total_errors} errors`),await $()}catch(s){n.error(`Discovery error: ${s instanceof Error?s.message:String(s)}`)}finally{u(!1)}},M=async e=>{var t;if(0!==e.length){v(!0);try{const{data:s}=await o.auth.getSession(),a=null==(t=s.session)?void 0:t.access_token;if(!a)return void n.error("Sign-in required");const r=await fetch(`${B}/ministry/ingest/review/confirm`,{method:"POST",headers:{Authorization:`Bearer ${a}`,"Content-Type":"application/json"},body:JSON.stringify({doc_ids:e})}),i=await r.json();if(!r.ok)return void n.error(`Confirm failed: ${i.error??r.statusText}`);n.success(`Confirmed ${i.confirmed} docs · queued for KG extraction`),await $()}finally{v(!1)}}},F=async e=>{var t;if(0!==e.length&&confirm(`Reject ${e.length} document${e.length>1?"s":""}? Files will be deleted.`)){v(!0);try{const{data:s}=await o.auth.getSession(),a=null==(t=s.session)?void 0:t.access_token;if(!a)return void n.error("Sign-in required");const r=await fetch(`${B}/ministry/ingest/review/reject`,{method:"POST",headers:{Authorization:`Bearer ${a}`,"Content-Type":"application/json"},body:JSON.stringify({doc_ids:e})}),i=await r.json();if(!r.ok)return void n.error(`Reject failed: ${i.error??r.statusText}`);n.success(`Rejected ${i.rejected} docs`),await $()}finally{v(!1)}}};if(!s)return null;const R=a.length>0&&a.every(e=>N.has(e.id));return e.jsxs("div",{className:"mb-12 rounded-xl border border-foreground
13/[0.08] bg-foreground/[0.015] px-6 py-6",children:[e.jsxs("div",{className:"mb-5 flex items-start justify-between gap-4",children:[e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(h,{className:"h-4 w-4 text-foreground/55"}),e.jsx("span",{className:"text-sm font-medium text-foreground/85",children:"Open-data discovery"}),a.length>0&&e.jsxs("span",{className:"ml-1 rounded-full bg-foreground/[0.08] px-2 py-0.5 text-[10px] uppercase tracking-wider text-foreground/65",children:[a.length," pending review"]})]}),e.jsx("p",{className:"mt-1 text-xs text-foreground/55 leading-relaxed max-w-2xl",children:"Crawls DHA, Daman, FCSC, MOHAP, U.AE, DOH, and the federal data.gov.ae catalogue. Files are downloaded but stay out of the knowledge graph until you confirm them below."})]}),e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsxs("button",{type:"button",onClick:()=>{E()},disabled:p,className:i("inline-flex items-center gap-2 rounded-md border border-foreground/15 px-3 py-1.5 text-xs font-medium",p?"opacity-60":"hover:bg-foreground
13/[0.04]"),children:[p?e.jsx(f,{className:"h-3 w-3 animate-spin"}):e.jsx(g,{className:"h-3 w-3"}),p?"Discoveringâ¦":"Run discovery (all sources)"]}),e.jsx("button",{type:"button",onClick:()=>{$()},disabled:c,className:"inline-flex items-center gap-1.5 rounded-md border border-foreground/10 px-2.5 py-1.5 text-xs text-foreground/65 hover:bg-foreground/[0.04]",title:"Refresh queue",children:e.jsx(b,{className:i("h-3 w-3",c&&"animate-spin")})})]})]}),e.jsx("div",{className:"mb-4 flex flex-wrap gap-1.5",children:W.map(t=>e.jsxs("button",{type:"button",onClick:()=>{E([t])},disabled:p,className:"rounded-md border border-foreground/10 px-2 py-1 text-[10px] uppercase tracking-wider text-foreground/55 hover:bg-foreground/[0.04] disabled:opacity-50",children:[G[t].split(" · ")[0],D[t]?e.jsxs("span",{className:"ml-1 text-foreground/40",children:["(",D[t],")"]}):null]},t))}),S&&e.jsxs("div",{className:"mb-4 rounded-md border border-foreground/[0.08] bg-foreground/[0.02] px-3 py-2 text-xs text-foreground/65",children:["Last run · ",S.staged," staged · ",S.duplicates," duplicates · ",S.errors," errors",S.by_source.length>0&&e.jsxs("span",{className:"ml-2 text-foreground/45",children:["(",S.by_source.map(e=>`${e.source}: ${e.staged}`).join(" · "),")"]})]}),e.jsxs("div",{className:"mb-3 flex items-center gap-3 text-xs",children:[e.jsx("span",{className:"text-foreground/45 uppercase tracking-wider",children:"Filter:"}),e.jsxs("select",{value:_,onChange:e=>C(e.target.value),className:"rounded-md border border-foreground
13/10 bg-transparent px-2 py-1 text-foreground/80 hover:bg-foreground/[0.03]",children:[e.jsx("option",{value:"all",children:"All sources"}),W.map(t=>e.jsx("option",{value:t,children:G[t]},t))]}),N.size>0&&e.jsxs("div",{className:"ml-auto flex items-center gap-2",children:[e.jsxs("span",{className:"text-foreground/55",children:[N.size," selected"]}),e.jsxs("button",{type:"button",onClick:()=>{M(Array.from(N))},disabled:x,className:"inline-flex items-center gap-1 rounded-md border border-emerald-500/40 bg-emerald-500/10 px-2.5 py-1 text-[11px] font-medium text-emerald-400 hover:bg-emerald-500/20 disabled:opacity-50",children:[e.jsx(y,{className:"h-3 w-3"})," Confirm"]}),e.jsxs("button",{type:"button",onClick:()=>{F(Array.from(N))},disabled:x,className:"inline-flex items-center gap-1 rounded-md border border-red-500/40 bg-red-500/10 px-2.5 py-1 text-[11px] font-medium text-red-400 hover:bg-red-500/20 disabled:opacity-50",children:[e.jsx(l,{className:"h-3 w-3"})," Reject"]})]})]}),c?e.jsxs("div",{className:"py-8 text-center text-sm text-foreground/45",children:[e.jsx(f,{className:"mx-auto mb-2 h-4 w-4 animate-spin"}),"Loading pending-review queueâ¦"]}):0===a.length?e.jsxs("div",{className:"rounded-md border border-dashed border-foreground
13/10 px-6 py-10 text-center text-sm text-foreground/55",children:["No documents awaiting review. Click ",e.jsx("strong",{children:"Run discovery"})," above to scan the federal + emirate-level open-data portals."]}):e.jsx("div",{className:"overflow-x-auto rounded-md border border-foreground/[0.06]",children:e.jsxs("table",{className:"w-full text-sm",children:[e.jsx("thead",{className:"bg-foreground/[0.025] text-[10px] uppercase tracking-wider text-foreground/55",children:e.jsxs("tr",{children:[e.jsx("th",{className:"w-8 px-3 py-2 text-left",children:e.jsx("input",{type:"checkbox",checked:R,onChange:()=>{k(R?new Set:new Set(a.map(e=>e.id)))},className:"cursor-pointer"})}),e.jsx("th",{className:"px-3 py-2 text-left font-medium",children:"File"}),e.jsx("th",{className:"px-3 py-2 text-left font-medium",children:"Source"}),e.jsx("th",{className:"px-3 py-2 text-left font-medium",children:"Domain"}),e.jsx("th",{className:"px-3 py-2 text-right font-medium",children:"Size"}),e.jsx("th",{className:"px-3 py-2 text-right font-medium",children:"Action"})]})}),e.jsx("tbody",{children:a.map(t=>{const s=N.has(t.id);
13return e.jsxs("tr",{className:"border-t border-foreground/[0.05] hover:bg-foreground/[0.02]",children:[e.jsx("td",{className:"px-3 py-2",children:e.jsx("input",{type:"checkbox",checked:s,onChange:()=>{k(e=>{const s=new Set(e);return s.has(t.id)?s.delete(t.id):s.add(t.id),s})},className:"cursor-pointer"})}),e.jsx("td",{className:"px-3 py-2 max-w-[280px]",children:e.jsxs("div",{className:"flex items-start gap-2 text-foreground/85",children:[e.jsx(j,{className:"mt-0.5 h-3.5 w-3.5 flex-shrink-0 text-foreground/45"}),e.jsx("span",{className:"truncate",title:t.filename,children:t.filename})]})}),e.jsx("td",{className:"px-3 py-2 text-foreground/65",children:e.jsxs("div",{className:"flex flex-col gap-0.5",children:[e.jsx("span",{className:"text-[11px]",children:G[t.source??""]??t.source??"â"}),t.source_url&&e.jsxs("a",{href:t.source_url,target:"_blank",rel:"noreferrer noopener",className:"inline-flex items-center gap-1 text-[10px] text-foreground/45 hover:text-foreground/75 truncate",title:t.source_url,children:[e.jsx(w,{className:"h-3 w-3 flex-shrink-0"}),e.jsx("span",{className:"truncate max-w-[220px]",children:t.source_url})]})]})}),e.jsx("td",{className:"px-3 py-2",children:e.jsx("span",{className:"rounded-full bg-foreground
13/[0.06] px-2 py-0.5 text-[10px] uppercase tracking-wider text-foreground/65",children:t.domain})}),e.jsx("td",{className:"px-3 py-2 text-right text-foreground/65 tabular-nums",children:(a=t.size_bytes,a?a<1024?`${a} B`:a<1048576?`${(a/1024).toFixed(1)} KB`:`${(a/1048576).toFixed(2)} MB`:"â")}),e.jsx("td",{className:"px-3 py-2",children:e.jsxs("div",{className:"flex items-center justify-end gap-1",children:[e.jsx("button",{type:"button",onClick:()=>{M([t.id])},disabled:x,className:"rounded-md border border-emerald-500/40 bg-emerald-500/10 px-2 py-0.5 text-[10px] font-medium text-emerald-400 hover:bg-emerald-500/20 disabled:opacity-50",children:"Confirm"}),e.jsx("button",{type:"button",onClick:()=>{F([t.id])},disabled:x,className:"rounded-md border border-red-500/40 bg-red-500/10 px-2 py-0.5 text-[10px] font-medium text-red-400 hover:bg-red-500/20 disabled:opacity-50",children:"Reject"})]})})]},t.id);var a})})]})})]})}const V=[{key:"strategy",label:"Strategy"},{key:"transformation",label:"Transformation"},{key:"legal",label:"Legal"},{key:"clinical",label:"Clinical"},{key:"public_health",label:"Public health"},{key:"regulatory",label:"Regulatory"},{key:"governance",label:"Governance"},{key:"workforce",label:"Workforce"},{key:"financial",label:"Financial"},{key:"general",label:"General"}],K=[{key:"public",label:"Public"},{key:"official",label:"Official",muted:!0},{key:"restricted",label:"Restricted"},{key:"confidential",label:"Confidential"}],X={pending:{label:"Pending upload",tone:"muted"},processing:{label:"Extracting",tone:"info"},indexed:{label:"Indexed",tone:"good"},failed:{label:"Failed",tone:"bad"},archived:{label:"Archived",tone:"muted"}};function Z(){const{user:s}=d(),{workspace:a}=r(),{hasWrite:i}=c(),[l,m]=t.useState([]),[p,u]=t.useState(!0),[x,h]=t.useState("all"),[f,g]=t.useState("all"),v=i("documents")||i("*"),b=t.useCallback(async()=>{if(!a)return;u(!0);let e=o.from("ministry_documents").select("id, filename, domain, classification, status, upload_date, uploaded_by, size_bytes, version, supersedes, extraction_error, kg_entity_id").eq("workspace_id",a.id).order("upload_date",{ascending:!1}).limit(200);"all"!==x&&(e=e.eq("status",x)),"all"!==f&&(e=e.eq("domain",f));const{data:t,error:s}=await e;s?n.error(`Failed to load documents: ${s.message}`):m(t??[]),u(!1)},[a,x,f]);return t.useEffect(()=>{b()},[b]),a?e.jsxs("div",{className:"mx-auto max-w-6xl px-8 py-12",children:[e.jsxs("div",{className:"mb-8",children:[e.jsx("div",{className:"text-[10px] uppercase tracking-widest text-foreground/35 font-medium",children:"M2 â Curated corpus"}),e.jsx("h1",{className:"mt-2 font-serif text-3xl text-foreground/95",children:"Document ingestion"}),e.jsx("p",{className:"mt-3 text-foreground/65 leading-relaxed max-w-2xl",children:"Upload Ministry documents into the approved source corpus. Domain and classification drive how the brief generator cites them and which roles can act on them."})]}),v&&e.jsx(Y,{workspaceId:a.id,userId:(null==s?void 0:s.id)??null,onUploaded:()=>{b()},existingDocs:l}),v&&e.jsx(J,{}),e.jsx(Q,{filterStatus:x,setFilterStatus:h,filterDomain:f,setFilterDomain:g,onRefresh:()=>{b()},loading:p}),e.jsx(ee,{docs:l,loading:p,canUpload:v,onChanged:()=>{b()}})]}):null}function Y({workspaceId:s,userId:a,onUploaded:r,existingDocs:i}){const[l,d]=t.useState(null),[c,m]=t.useState("strategy"),[p,u]=t.useState("official"),[x,h]=t.useState(""),[f,g]=t.useState(!1),v=()=>{d(null),m("strategy"),u("official"),h("")},b=new Set(i.map(e=>e.supersedes).filter(Boolean)),y=i.filter(e=>"archived"!==e.status&&!b.has(e.id));return e.jsxs("form",{onSubmit:async e=>{if(e.preventDefault(),l){g(!0);try{const e=crypto.randomUUID(),t=l.name.replace(/[^a-zA-Z0-9._-]/g,"_"),i=`${s}/${e}/${t}`,{error:d}=await o.storage.from("ministry-documents").upload(i,l,{cacheControl:"3600",contentType:l.type||"application/octet-stream",upsert:!1});if(d)return n.error(`Upload failed: ${d.message}`),void g(!1);const{error:m}=await o.from("ministry_documents").insert({id:e,workspace_id:s,filename:l.name,storage_path:i,mime_type:l.type||null,size_bytes:l.size,domain:c,classification:p,uploaded_by:a,status:"processing",supersedes:x||null});if(m)return await o.storage.from("ministry-documents").remove([i]),n.error(`Failed to record document: ${m.message}`),void g(!1);n.success(x?`Uploaded ${l.name} as a new version`:`Uploaded ${l.name}. Extraction will run shortly.`),window.dispatchEvent(new CustomEvent("mohap:document-uploaded",{detail:{document_id:e,filename:l.name,domain:c,classification:p}})),v(),r()}finally{g(!1)}}else n.error("Pick a file to upload")}
13,className:"mb-10 rounded-xl border border-foreground/[0.08] bg-foreground/[0.015] px-6 py-6",style:{borderColor:"var(--ministry-accent, currentColor)"},children:[e.jsxs("div",{className:"mb-4 flex items-center gap-2",children:[e.jsx(N,{className:"h-4 w-4 text-foreground/55"}),e.jsx("span",{className:"text-sm font-medium text-foreground/85",children:"Upload a document"})]}),e.jsxs("div",{className:"grid gap-4 md:grid-cols-2",children:[e.jsxs("label",{className:"block",children:[e.jsx("span",{className:"text-xs uppercase tracking-wider text-foreground/50 font-medium",children:"File"}),e.jsx("input",{type:"file",onChange:e=>{var t;return d((null==(t=e.target.files)?void 0:t[0])??null)},className:"mt-1 block w-full text-sm text-foreground/80 file:mr-3 file:rounded-md file:border-0 file:bg-foreground/[0.06] file:px-3 file:py-1.5 file:text-xs file:font-medium hover:file:bg-foreground/[0.1] file:cursor-pointer",accept:".pdf,.doc,.docx,.xls,.xlsx,.ppt,.pptx,.txt,.md,.csv",required:!0})]}),e.jsxs("label",{className:"block",children:[e.jsx("span",{className:"text-xs uppercase tracking-wider text-foreground/50 font-medium",children:"Domain"}),e.jsx("select",{value:c,onChange:e=>m(e.target.value),className:"mt-1 block w-full rounded-md border border-foreground
13/[0.12] bg-background px-3 py-2 text-sm text-foreground/85 focus:outline-none focus:border-foreground/30",children:V.map(t=>e.jsx("option",{value:t.key,children:t.label},t.key))})]}),e.jsxs("label",{className:"block",children:[e.jsx("span",{className:"text-xs uppercase tracking-wider text-foreground/50 font-medium",children:"Classification"}),e.jsx("select",{value:p,onChange:e=>u(e.target.value),className:"mt-1 block w-full rounded-md border border-foreground/[0.12] bg-background px-3 py-2 text-sm text-foreground/85 focus:outline-none focus:border-foreground/30",children:K.map(t=>e.jsx("option",{value:t.key,children:t.label},t.key))})]}),e.jsxs("label",{className:"block",children:[e.jsx("span",{className:"text-xs uppercase tracking-wider text-foreground/50 font-medium",children:"Supersedes (optional)"}),e.jsxs("select",{value:x,onChange:e=>h(e.target.value),className:"mt-1 block w-full rounded-md border border-foreground/[0.12] bg-background px-3 py-2 text-sm text-foreground/85 focus:outline-none focus:border-foreground/30",children:[e.jsx("option",{value:"",children:"â Net new document â"}),y.map(t=>e.jsxs("option",{value:t.id,children:["v",t.version,": ",t.filename]},t.id))]})]})]}),e.jsxs("div",{className:"mt-5 flex items-center justify-end gap-3",children:[e.jsx("button",{type:"button",onClick:v,disabled:f,className:"px-4 py-1.5 text-sm text-foreground/60 hover:text-foreground/85 rounded-md transition disabled:opacity-40",children:"Reset"}),e.jsx("button",{type:"submit",disabled:f||!l,className:"px-5 py-1.5 text-sm bg-foreground text-background rounded-md hover:bg-foreground
13/90 transition disabled:opacity-40",children:f?"Uploadingâ¦":"Upload"})]})]})}function Q({filterStatus:t,setFilterStatus:s,filterDomain:a,setFilterDomain:r,onRefresh:o,loading:n}){return e.jsxs("div",{className:"mb-4 flex items-center gap-3",children:[e.jsxs("select",{value:t,onChange:e=>s(e.target.value),className:"rounded-md border border-foreground/[0.1] bg-background px-2.5 py-1.5 text-xs text-foreground/75 focus:outline-none focus:border-foreground/25",children:[e.jsx("option",{value:"all",children:"All statuses"}),Object.entries(X).map(([t,s])=>e.jsx("option",{value:t,children:s.label},t))]}),e.jsxs("select",{value:a,onChange:e=>r(e.target.value),className:"rounded-md border border-foreground/[0.1] bg-background px-2.5 py-1.5 text-xs text-foreground/75 focus:outline-none focus:border-foreground/25",children:[e.jsx("option",{value:"all",children:"All domains"}),V.map(t=>e.jsx("option",{value:t.key,children:t.label},t.key))]}),e.jsxs("button",{onClick:o,disabled:n,className:"ml-auto flex items-center gap-1.5 rounded-md px-2.5 py-1.5 text-xs text-foreground/60 hover:text-foreground/85 hover:bg-foreground
13/[0.04] transition disabled:opacity-40",children:[e.jsx(b,{className:i("h-3.5 w-3.5",n&&"animate-spin")}),"Refresh"]})]})}function ee({docs:t,loading:s,canUpload:a,onChanged:r}){return s&&0===t.length?e.jsx("div",{className:"py-16 text-center text-sm text-foreground/40",children:"Loadingâ¦"}):0===t.length?e.jsxs("div",{className:"py-16 text-center text-sm text-foreground/45 leading-relaxed",children:["No documents in the corpus yet.",e.jsx("br",{}),a?"Upload the first document above to bootstrap the brief generator.":"Wait for an admin to upload the first documents."]}):e.jsx("div",{className:"space-y-2",children:t.map(t=>e.jsx(te,{doc:t,canUpload:a,onChanged:r},t.id))})}function te({doc:t,canUpload:s,onChanged:a}){const r=X[t.status]??X.pending,l="indexed"===t.status?k:"failed"===t.status?_:"archived"===t.status?v:C;return e.jsxs("div",{className:"flex items-center gap-4 rounded-lg border border-foreground/[0.06] px-4 py-3 hover:border-foreground/[0.18] transition",children:[e.jsx(j,{className:"h-4 w-4 text-foreground/45 flex-shrink-0"}),e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsxs("div",{className:"flex items-center gap-2 text-[14px] text-foreground/90",children:[e.jsx("span",{className:"font-medium truncate",children:t.filename}),t.version>1&&e.jsxs("span",{className:"text-[11px] text-foreground/45",children:["v",t.version]})]}),e.jsxs("div",{className:"flex items-center gap-3 mt-0.5 text-[11px] text-foreground/55",children:[e.jsx("span",{className:"uppercase tracking-wider",children:t.domain.replace(/_/g," ")}),e.jsx("span",{children:"·"}),e.jsx("span",{className:"uppercase tracking-wider",children:t.classification}),t.size_bytes&&e.jsxs(e.Fragment,{children:[e.jsx("span",{children:"·"}),e.jsx("span",{children:se(t.size_bytes)})]})]}),t.extraction_error&&e.jsx("div",{className:"mt-1 text-[11px] text-rose-500/85 truncate",children:t.extraction_error})]}),e.jsxs("div",{className:i("flex items-center gap-1.5 text-[11px] font-medium uppercase tracking-wider flex-shrink-0","good"===r.tone?"text-emerald-600/85":"info"===r.tone?"text-amber-600/85":"bad"===r.tone?"text-rose-500/85":"text-foreground/50"),children:[e.jsx(l,{className:"h-3.5 w-3.5"}),r.label]}),s&&"archived"!==t.status&&e.jsx("button",{onClick:async()=>{const{error:e}=await o.from("ministry_documents").update({status:"archived"}).eq("id",t.id);e?n.error(`Archive failed: ${e.message}`):(n.success("Archived"),a())},className:"text-[11px] text-foreground/40 hover:text-foreground/75 transition flex-shrink-0",children:"Archive"})]})}function se(e){return e<1024?`${e} B`:e<1048576?`${(e/1024).toFixed(0)} KB`:e<1073741824?`${(e/1024/1024).toFixed(1)} MB`:`${(e/1024/1024/1024).toFixed(2)} GB`}const ae=[{id:"hie",label:"Health Information Exchange",description:"Federal HIE patient-data feed (read-only). FHIR R4 bulk export.",icon:S,status:"not_configured"},{id:"doh-feed",label:"Department of Health feed",description:"Abu Dhabi DoH surveillance + licensing event stream.",icon:z,status:"not_configured"},{id:"moccae",label:"MoCCAE coordination",description:"Animal-health AMR coordination (intergovernmental webhook).",icon:z,status:"not_configured"},{id:"ubrjsa",label:"Federal Cabinet Secretariat",description:"Cabinet decision feed (intergovernmental).",icon:z,status:"not_configured"},{id:"calendar",label:"Ministerial calendar",description:"Outlook calendar feed for Minister + MO scheduling.",icon:D,status:"not_configured"},{id:"email-intake",label:"Email intake inbox",description:"Forward stakeholder correspondence to [email protected].",icon:E,status:"not_configured"},{id:"scheduled",label:"Scheduled ingestion",description:"pg_cron schedules â morning + afternoon brief generation.",icon:M,status:"live"}];function re(){return e.jsxs("div",{className:"mx-auto max-w-5xl px-6 py-10",children:[e.jsxs("div",{className:"mb-6",children:[e.jsx("div",{className:"mohap-section-label",children:"Connect space"}),e.jsx("h2",{className:"mt-1 text-[20px] font-semibold",style:{color:"var(--mohap-text-primary)"},children:"API connections + ingestion"}),e.jsx("p",{className:"mt-2 text-[13px] max-w-2xl",style:{color:"var(--mohap-text-secondary)"},children:"Channels through which the Ministry corpus and signals flow into the agent. Direct API connections, webhook endpoints, scheduled jobs."})]}),e.jsx("div",{className:"space-y-2",children:ae.map(t=>{const s=t.icon;return e.jsxs("div",{className:"mohap-card p-4 flex items-start gap-4",children:[e.jsx("div",{className:"w-9 h-9 rounded-md flex items-center justify-center flex-shrink-0",style:{background:"var(--mohap-surface-tertiary)"},children:e.jsx(s,{className:"h-4 w-4",style:{color:"var(--mohap-text-secondary)"}})}),e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsx("div",{className:"text-[14px] font-medium",style:{color:"var(--mohap-text-primary)"},children:t.label}),e.jsx("p",{className:"mt-0.5 text-[12px]",style:{color:"var(--mohap-text-secondary)"},children:t.description})]}),e.jsx("span",{className:i("mohap-pill flex-shrink-0","live"===t.status?"mohap-pill--rag-green":"draft"===t.status?"mohap-pill--rag-amber":""),children:"live"===t.status?"Live":"draft"===t.status?"Draft":"Not configured"})]},t.id)})}),e.jsx("div",{className:"mt-8",children:e.jsx(oe,{})})]})}function oe(){const[s,a]=t.useState([]);return t.useEffect(()=>{const e=e=>{const t=e.detail;a(e=>[{id:t.document_id,filename:t.filename,domain:t.domain,at:Date.now()},...e].slice(0,8))};return window.addEventListener("mohap:document-uploaded",e),()=>window.removeEventListener("mohap:document-uploaded",e)},[]),e.jsxs("div",{className:"mohap-card p-5",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-3",children:[e.jsx(F,{className:"h-4 w-4",style:{color:"var(--mohap-accent)"}}),e.jsx("div",{className:"mohap-section-label",children:"Live ingestion · memory graph pulse"})]}),e.jsx("p",{className:"text-[13px] mb-4",style:{color:"var(--mohap-text-secondary)"},children:"Documents uploaded under the Documents tab flow through the extraction pipeline. The Ministry knowledge graph populates as entities are extracted; the institutional-memory view (rendered in chat on request) reflects the current state in near-real-time."}),0===s.length?e.jsxs("div",{className:"text-[12px]",style:{color:"var(--mohap-text-muted)"},children:["No recent uploads in this session. Upload a document under the ",e.jsx("strong",{children:"Documents"})," tab to see the graph pulse."]}):e.jsx("div",{className:"space-y-1.5",children:s.map(t=>{const s=Date.now()-t.at,a=s<8e3;return e.jsxs("div",{className:i("flex items-center gap-3 rounded-md px-3 py-2 transition",a&&"animate-pulse"),style:{background:a?"var(--mohap-accent-light)":"var(--mohap-surface-secondary)",borderLeft:"3px solid "+(a?"var(--mohap-accent)":"var(--mohap-border)")},children:[e.jsx(F,{className:"h-3.5 w-3.5 flex-shrink-0",style:{color:a?"var(--mohap-accent)":"var(--mohap-text-muted)"}}),e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsx("div",{className:"text-[13px] truncate",style:{color:"var(--mohap-text-primary)"},children:t.filename}),e.jsx("div",{className:"text-[10px] uppercase tracking-wider mt-0.5",style:{color:"var(--mohap-text-muted)"},children:t.domain.replace(/_/g," ")})]}),e.jsx("span",{className:"text-[10px] flex-shrink-0",style:{color:"var(--mohap-text-muted)"},children:a?"extractingâ¦":`${Math.round(s/1e3)}s ago`})]},`${t.id}-${t.at}`)})})]})}function ne(){const{workspace:s}=r(),[a,n]=t.useState([]),[i,l]=t.useState([]);return t.useEffect(()=>{s&&(async()=>{const[{data:e},{data:t}]=await Promise.all([o.from("ministry_governance_policies").select("*").eq("workspace_id",s.id).order("policy_key"),o.from("ministry_review_domains").select("*").eq("workspace_id",s.id).order("domain_key")]);n(e??[]),l(t??[])})()},[s]),e.jsxs("div",{className:"mx-auto max-w-5xl px-6 py-10 space-y-10",children:[e.jsxs("section",{children:[e.jsx("div",{className:"mohap-section-label",children:"Governance"}),e.jsxs("h2",{className:"mt-1 text-[20px] font-semibold",style:{color:"var(--mohap-text-primary)"},children:["Prohibited actions (",a.length,")"]}),e.jsx("p",{className:"mt-2 text-[13px] max-w-2xl mb-5",style:{color:"var(--mohap-text-secondary)"},children:"The agent is structurally blocked from taking these actions. When matched, output is suppressed and routed to the named review domain."}),e.jsx("div",{className:"space-y-2",children:a.map(t=>e.jsxs("div",{className:"mohap-card p-4 flex items-start gap-4",children:[e.jsx(R,{className:"h-4 w-4 flex-shrink-0 mt-0.5",style:{color:"var(--mohap-danger)"}}),e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-0.5",children:[e.jsx("span",{className:"text-[14px] font-medium",style:{color:"var(--mohap-text-primary)"},children:t.policy_label}),t.active&&e.jsx("span",{className:"mohap-pill mohap-pill--rag-green",children:"Active"})]}),e.jsx("p",{className:"text-[12px] mb-1.5",style:{color:"var(--mohap-text-secondary)"},children:t.description}),e.jsxs("div",{className:"flex flex-wrap gap-1.5 text-[10px]",style:{color:"var(--mohap-text-muted)"},children:[t.match_keywords.slice(0,8).map(t=>e.jsx("span",{className:"px-1.5 py-0.5 rounded font-mono",style:{background:"var(--mohap-surface-tertiary)"},children:t},t)),t.match_keywords.length>8&&e.jsxs("span",{children:["+",t.match_keywords.length-8]})]}),t.routed_review_domain&&e.jsxs("div",{className:"mt-1.5 text-[11px]",style:{color:"var(--mohap-text-muted)"},children:["Routes to: ",e.jsx("strong",{children:t.routed_review_domain})]})]})]},t.id))})]}),e.jsxs("section",{children:[e.jsxs("h2",{className:"text-[20px] font-semibold",style:{color:"var(--mohap-text-primary)"},children:["Review domains (",i.length,")"]}),e.jsx("p",{className:"mt-2 text-[13px] max-w-2xl mb-5",style:{color:"var(--mohap-text-secondary)"},children:"Expert review queues. Decisions, options papers, and risks are auto-routed to the relevant domain based on classifier output and policy matches."}),e.jsx("div",{className:"grid grid-cols-2 gap-3",children:i.map(t=>e.jsxs("div",{className:"mohap-card p-4",children:[e.jsxs("div",{className:"flex items-start justify-between gap-2 mb-1",children:[e.jsx("div",{className:"text-[14px] font-medium",style:{color:"var(--mohap-text-primary)"},children:t.domain_label}),e.jsxs("span",{className:"text-[10px] uppercase tracking-wider",style:{color:"var(--mohap-text-muted)"},children:["SLA ",t.sla_hours,"h"]})]}),t.description&&e.jsx("p",{className:"text-[12px]",style:{color:"var(--mohap-text-secondary)"},children:t.description}),e.jsxs("div",{className:"mt-2 flex items-center gap-1.5 text-[11px]",style:{color:"var(--mohap-text-muted)"},children:[e.jsx(m,{className:"h-3 w-3"}),t.required_role_keys.join(", ")||"â"]}
13)]},t.id))})]})]})}function ie(){const{workspace:s}=r(),[a,n]=t.useState([]),[l,d]=t.useState(!0),[c,m]=t.useState("all"),[p,u]=t.useState("all"),x=t.useCallback(async()=>{if(!s)return;d(!0);let e=o.from("audit_events").select("id, user_id, action, resource_type, resource_id, metadata, created_at").eq("workspace_id",s.id).order("created_at",{ascending:!1}).limit(500);"all"!==c&&(e=e.like("action",`${c}%`)),"all"!==p&&(e=e.eq("resource_type",p));const{data:t}=await e;n(t??[]),d(!1)},[s,c,p]);t.useEffect(()=>{x()},[x]),t.useEffect(()=>{const e=setInterval(()=>{x()},5e3),t=()=>{x()};return window.addEventListener("focus",t),()=>{clearInterval(e),window.removeEventListener("focus",t)}},[x]);const h=Array.from(new Set(a.map(e=>e.action.split(".")[0]))).sort(),f=Array.from(new Set(a.map(e=>e.resource_type))).sort();return e.jsxs("div",{className:"mx-auto max-w-6xl px-6 py-10",children:[e.jsxs("div",{className:"mb-6 flex items-end justify-between gap-4",children:[e.jsxs("div",{children:[e.jsx("div",{className:"mohap-section-label",children:"Audit"}),e.jsx("h2",{className:"mt-1 text-[20px] font-semibold",style:{color:"var(--mohap-text-primary)"},children:"Audit log"}),e.jsx("p",{className:"mt-2 text-[13px] max-w-2xl",style:{color:"var(--mohap-text-secondary)"},children:"Append-only record of every governance-relevant action. DELETE and UPDATE are blocked at the database layer."})]}),e.jsxs("button",{onClick:x,disabled:l,className:"flex items-center gap-1.5 px-3 py-1.5 text-[12px] rounded-md disabled:opacity-50",style:{background:"var(--mohap-surface)",border:"1px solid var(--mohap-border)",color:"var(--mohap-text-secondary)"},children:[e.jsx(b,{className:i("h-3.5 w-3.5",l&&"animate-spin")}),"Refresh"]})]}),e.jsxs("div",{className:"flex items-center gap-3 mb-4",children:[e.jsxs("select",{value:c,onChange:e=>m(e.target.value),className:"rounded-md border bg-white px-2.5 py-1.5 text-[12px]",style:{borderColor:"var(--mohap-border)"},children:[e.jsx("option",{value:"all",children:"All actions"}),h.map(t=>e.jsxs("option",{value:t,children:[t,".*"]},t))]}),e.jsxs("select",{value:p,onChange:e=>u(e.target.value),className:"rounded-md border bg-white px-2.5 py-1.5 text-[12px]",style:{borderColor:"var(--mohap-border)"},children:[e.jsx("option",{value:"all",children:"All resources"}),f.map(t=>e.jsx("option",{value:t,children:t},t))]})]}),l&&0===a.length?e.jsx("div",{className:"py-16 text-center text-sm",style:{color:"var(--mohap-text-muted)"},children:"Loadingâ¦"}):0===a.length?e.jsxs("div",{className:"mohap-card p-10 text-center",children:[e.jsx(A,{className:"h-8 w-8 mx-auto mb-3",style:{color:"var(--mohap-text-muted)"}}),e.jsx("h3",{className:"text-[14px] font-semibold mb-1",style:{color:"var(--mohap-text-primary)"},children:"No audit events"})]}):e.jsx("div",{className:"mohap-card overflow-x-auto",children:e.jsxs("table",{className:"w-full text-[12px]",children:[e.jsx("thead",{children:e.jsxs("tr",{style:{background:"var(--mohap-surface-tertiary)"},children:[e.jsx("th",{className:"text-left px-3 py-2",children:"Time"}),e.jsx("th",{className:"text-left px-3 py-2",children:"Action"}),e.jsx("th",{className:"text-left px-3 py-2",children:"Resource"}),e.jsx("th",{className:"text-left px-3 py-2",children:"Resource id"}),e.jsx("th",{className:"text-left px-3 py-2",children:"User"})]})}),e.jsx("tbody",{children:a.map(t=>{var s,a;return e.jsxs("tr",{className:"border-t align-top",style:{borderColor:"var(--mohap-border)"},children:[e.jsx("td",{className:"px-3 py-2 whitespace-nowrap",children:new Date(t.created_at).toLocaleString()}),e.jsx("td",{className:"px-3 py-2 font-mono text-[11px]",children:t.action}),e.jsx("td",{className:"px-3 py-2",children:t.resource_type}),e.jsxs("td",{className:"px-3 py-2 font-mono text-[11px]",children:[(null==(s=t.resource_id)?void 0:s.slice(0,12))??"â","â¦"]}),e.jsx("td",{className:"px-3 py-2 font-mono text-[11px]",children:(null==(a=t.user_id)?void 0:a.slice(0,8))??"system"})]},t.id)})})]})})]})}function le({workspace_id:s,entity_id:a,onClose:r,initial_chunk_id:o}){const[n,d]=t.useState(null),[c,m]=t.useState(!0),[u,x]=t.useState(null),[h,g]=t.useState(o?"clauses":"what"),[v,b]=t.useState(o??null);t.useEffect(()=>{let e=!1;return m(!0),x(null),(async()=>{try{const t=`/evidence/entities/${encodeURIComponent(a)}/sources`,r=await p(t,s,{method:"GET"});if(!r)throw new Error("Empty response");e||d(r)}catch(t){e||x(t instanceof Error?t.message:String(t))}finally{e||m(!1)}})(),()=>{e=!0}},[s,a]);const y=t.useMemo(()=>n?n.sources.flatMap(e=>e.chunks.map(t=>({...t,source:e}))):[],[n]),w=t.useMemo(()=>y.find(e=>e.chunk_id===v)??null,[y,v]);return e.jsxs("div",{className:"flex h-full flex-col border-l border-foreground
13/[0.08] bg-foreground/[0.015]",children:[e.jsxs("div",{className:"flex items-start justify-between gap-3 border-b border-foreground/[0.06] px-5 py-4",children:[e.jsxs("div",{children:[e.jsx("div",{className:"text-[10px] uppercase tracking-widest text-foreground/40",children:"Entity"}),e.jsx("div",{className:"mt-1 font-serif text-lg text-foreground/95",children:(null==n?void 0:n.entity.name)??(null==n?void 0:n.entity.canonical_name)??"â"}),e.jsxs("div",{className:"mt-1 flex flex-wrap items-center gap-1.5 text-[10px] uppercase tracking-wider text-foreground/55",children:[(null==n?void 0:n.entity.type)&&e.jsx("span",{className:"rounded-full bg-foreground/[0.06] px-2 py-0.5",children:n.entity.type}),n&&e.jsxs("span",{children:[n.total_evidence_docs," supporting doc",1===n.total_evidence_docs?"":"s"]})]})]}),r&&e.jsx("button",{type:"button",onClick:r,className:"rounded-md p-1 text-foreground/55 hover:bg-foreground/[0.06]","aria-label":"Close panel",children:e.jsx(l,{className:"h-4 w-4"})})]}),e.jsx("div",{className:"flex border-b border-foreground
13/[0.06] px-5",children:[{id:"what",label:"What we know",Icon:I},{id:"sources",label:"Sources",Icon:j},{id:"clauses",label:"Clauses",Icon:L},{id:"tables",label:"Tables",Icon:H}].map(({id:t,label:s,Icon:a})=>e.jsxs("button",{type:"button",onClick:()=>g(t),className:i("inline-flex items-center gap-1.5 border-b-2 px-3 py-2 text-xs font-medium",h===t?"border-foreground/85 text-foreground/95":"border-transparent text-foreground/55 hover:text-foreground/80"),children:[e.jsx(a,{className:"h-3 w-3"}),s]},t))}),e.jsxs("div",{className:"flex-1 overflow-y-auto",children:[c&&e.jsxs("div",{className:"flex h-full items-center justify-center text-sm text-foreground/45",children:[e.jsx(f,{className:"mr-2 h-4 w-4 animate-spin"}),"Loading drilldownâ¦"]}),u&&e.jsxs("div",{className:"px-5 py-6 text-sm text-red-400",children:["Failed to load entity sources: ",u]}),!c&&!u&&n&&e.jsxs(e.Fragment,{children:["what"===h&&e.jsx("div",{className:"px-5 py-5 text-sm text-foreground/85 leading-relaxed",children:n.what_we_know}),"sources"===h&&e.jsx(de,{sources:n.sources,onChunkClick:e=>{g("clauses"),b(e)}}),"clauses"===h&&e.jsx(ce,{chunks:y,activeChunkId:v,onSelect:e=>b(e),activeChunk:w}),"tables"===h&&e.jsx("div",{className:"px-5 py-5 text-sm text-foreground/55",children:"Table-cell evidence appears here once XLSX-backed entities flow through M14."})]})]})]})}function de({sources:t,onChunkClick:s}){return 0===t.length?e.jsx("div",{className:"px-5 py-6 text-sm text-foreground/55",children:"No supporting documents are linked to this entity yet. The entity exists in the knowledge graph but has not been bridged to the evidence layer."}
13):e.jsx("ul",{className:"divide-y divide-foreground/[0.06]",children:t.map((t,a)=>e.jsxs("li",{className:"px-5 py-4",children:[e.jsxs("div",{className:"flex items-start justify-between gap-3",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsx("div",{className:"font-medium text-sm text-foreground/90 truncate",children:t.doc_title??"(untitled)"}),e.jsxs("div",{className:"mt-1 flex flex-wrap items-center gap-1.5 text-[10px] uppercase tracking-wider text-foreground/45",children:[e.jsx("span",{children:t.source_system.replace(/_/g," ")}),t.published_at&&e.jsxs("span",{children:["· ",new Date(t.published_at).toLocaleDateString()]}),e.jsx(q,{freshness:t.freshness,size:"xs"})]})]}),t.source_url&&e.jsx("a",{href:t.source_url,target:"_blank",rel:"noreferrer noopener",className:"flex-shrink-0 text-foreground/45 hover:text-foreground/75",title:t.source_url,children:e.jsx(w,{className:"h-3.5 w-3.5"})})]}),t.chunks.length>0&&e.jsx("ul",{className:"mt-3 space-y-1.5",children:t.chunks.map(t=>e.jsx("li",{children:e.jsxs("button",{type:"button",onClick:()=>s(t.chunk_id),className:"block w-full rounded-md border border-transparent px-2 py-1.5 text-left text-xs text-foreground/75 hover:border-foreground
13/[0.1] hover:bg-foreground/[0.04]",children:[e.jsxs("div",{className:"text-[10px] uppercase tracking-wider text-foreground/45",children:[t.section_path.join(" ⺠")||"â",t.page_start>0&&e.jsxs(e.Fragment,{children:[" · p. ",t.page_start,t.page_end!==t.page_start?`â${t.page_end}`:""]})]}),e.jsx("div",{className:"mt-1 line-clamp-3",children:t.text})]})},t.chunk_id))})]},`${t.evidence_doc_id??t.raw_event_id}-${a}`))})}function ce({chunks:t,activeChunkId:s,activeChunk:a,onSelect:r}){return 0===t.length?e.jsx("div",{className:"px-5 py-6 text-sm text-foreground/55",children:"No clause-level evidence yet."}):e.jsxs("div",{className:"grid h-full grid-cols-[300px_1fr]",children:[e.jsx("ul",{className:"overflow-y-auto border-r border-foreground/[0.06] divide-y divide-foreground/[0.04]",children:t.map(t=>e.jsx("li",{children:e.jsxs("button",{type:"button",onClick:()=>r(t.chunk_id),className:i("block w-full px-4 py-3 text-left text-xs",s===t.chunk_id?"bg-foreground/[0.06] text-foreground/95":"text-foreground/75 hover:bg-foreground
13/[0.03]"),children:[e.jsx("div",{className:"text-[10px] uppercase tracking-wider text-foreground/45 truncate",children:t.source.doc_title??"(untitled)"}),e.jsx("div",{className:"mt-0.5 truncate",children:t.section_path.join(" ⺠")||"â"}),e.jsxs("div",{className:"mt-1 text-[10px] text-foreground/40",children:["p. ",t.page_start,t.page_end!==t.page_start?`â${t.page_end}`:""]})]})},t.chunk_id))}),e.jsx("div",{className:"overflow-y-auto px-6 py-5",children:a?e.jsxs("article",{className:"max-w-prose",children:[e.jsxs("header",{className:"mb-3",children:[e.jsx("div",{className:"text-[10px] uppercase tracking-wider text-foreground/45",children:a.source.doc_title}),e.jsx("h3",{className:"mt-1 font-serif text-lg text-foreground/95",children:a.section_path[a.section_path.length-1]??"Clause"}),e.jsxs("div",{className:"mt-1 flex flex-wrap items-center gap-2 text-[10px] uppercase tracking-wider text-foreground/55",children:[e.jsxs("span",{children:["p. ",a.page_start,a.page_end!==a.page_start?`â${a.page_end}`:""]}),e.jsx(q,{freshness:a.source.freshness,size:"xs"})]})]}),e.jsx("div",{className:"text-sm leading-relaxed text-foreground/85 whitespace-pre-wrap",children:a.text})]}):e.jsx("div",{className:"text-sm text-foreground/45",children:"Select a clause from the list to render it here."})})]})}const me=x(()=>T(()=>import("./ContextGraph-2adCX-MV.js"),["assets/ContextGraph-2adCX-MV.js","assets/ui-vendor-CBbdTawN.js","assets/react-vendor-DQSFk_7t.js","assets/three.module-C9pbPSLs.js","assets/index-DNEY-jN9.js","assets/supabase-NZ2Vt4Mp.js","assets/chart-vendor-Dq0yAQdW.js","assets/form-vendor-CzIjS8Un.js","assets/index-CoidcMIn.css"]).then(e=>({default:e.ContextGraph})));function pe(){const{workspace:s}=r(),[a,n]=t.useState(null),[l,d]=t.useState(!0),[c,m]=t.useState(null),[p,x]=t.useState(null),h=t.useCallback(async()=>{if(!s)return;d(!0);const e=s.id,[t,a,r,i,l,c]=await Promise.all([o.from("kg_entities").select("id",{count:"exact",head:!0}).eq("workspace_id",e),o.from("kg_edges").select("id",{count:"exact",head:!0}).eq("workspace_id",e),o.from("ministry_documents").select("id",{count:"exact",head:!0}).eq("workspace_id",e).eq("status","indexed"),o.from("ministry_decisions").select("id",{count:"exact",head:!0}).eq("workspace_id",e),o.from("ministry_risks").select("id",{count:"exact",head:!0}).eq("workspace_id",e),o.from("ministry_initiatives").select("id",{count:"exact",head:!0}).eq("workspace_id",e)]);n({entities:t.count??0,edges:a.count??0,documents:r.count??0,decisions:i.count??0,risks:l.count??0,initiatives:c.count??0}),d(!1)},[s]);return t.useEffect(()=>{h()},[h]),t.useEffect(()=>{const e=()=>{h()};return window.addEventListener("mohap:document-uploaded",e),()=>window.removeEventListener("mohap:document-uploaded",e)},[h]),s?e.jsxs("div",{className:"flex flex-col h-full",children:[e.jsxs("header",{className:"flex-shrink-0 px-6 py-4 border-b",style:{borderColor:"var(--mohap-border)",background:"var(--mohap-surface)"},children:[e.jsxs("div",{className:"flex items-start justify-between gap-4",children:[e.jsxs("div",{children:[e.jsx("div",{className:"mohap-section-label",children:"Memory"}),e.jsxs("h2",{className:"mt-1 text-[20px] font-semibold flex items-center gap-2",style:{color:"var(--mohap-text-primary)"},children:[e.jsx(I,{className:"h-5 w-5",style:{color:"var(--mohap-primary)"}}),"Institutional memory"]}),e.jsx("p",{className:"mt-1 text-[13px] max-w-2xl",style:{color:"var(--mohap-text-secondary)"},children:"Decisions, risks, initiatives, and the documents they originate from. Click any node to drill into its provenance and relationships."})]}),e.jsxs("button",{onClick:h,disabled:l,className:"flex items-center gap-1.5 px-3 py-1.5 text-[12px] rounded-md disabled:opacity-50",style:{background:"var(--mohap-surface-secondary)",color:"var(--mohap-text-secondary)",border:"1px solid var(--mohap-border)"},children:[e.jsx(b,{className:i("h-3.5 w-3.5",l&&"animate-spin")}),"Refresh"]})]}),a&&e.jsxs("div",{className:"grid grid-cols-6 gap-2 mt-4",children:[e.jsx(ue,{label:"Entities",value:a.entities.toLocaleString()}
13),e.jsx(ue,{label:"Edges",value:a.edges.toLocaleString()}),e.jsx(ue,{label:"Documents",value:a.documents.toString()}),e.jsx(ue,{label:"Decisions",value:a.decisions.toString()}),e.jsx(ue,{label:"Risks",value:a.risks.toString()}),e.jsx(ue,{label:"Initiatives",value:a.initiatives.toString()})]})]}),e.jsxs("div",{className:i("flex-1 min-h-0 relative",c&&"grid grid-cols-[1fr_min(560px,40%)]"),style:{background:"linear-gradient(180deg, var(--mohap-primary-dark) 0%, var(--mohap-primary) 100%)"},children:[e.jsx(t.Suspense,{fallback:e.jsx("div",{className:"p-8 text-sm text-white/85",children:"Loading institutional memoryâ¦"}),children:a&&a.entities+a.edges>0?e.jsx(me,{workspaceId:s.id,workerFetch:u,entityCount:a.entities,edgeCount:a.edges,onEntityClick:e=>{m(e),x(null)}}):e.jsxs("div",{className:"absolute inset-0 flex flex-col items-center justify-center text-white/85 p-8 text-center",children:[e.jsx(I,{className:"h-10 w-10 mb-3 opacity-80"}),e.jsx("div",{className:"text-[15px] font-semibold mb-1",children:"Empty institutional memory"}),e.jsx("div",{className:"text-[12px] opacity-80 max-w-md",children:"Upload documents under the Documents tab. The extraction pipeline will populate the memory graph; new entities pulse in as they're indexed."})]})}),c&&e.jsx(le,{workspace_id:s.id,entity_id:c,initial_chunk_id:p??void 0,onClose:()=>{m(null),x(null)}})]})]}):null}function ue({label:t,value:s}){return e.jsxs("div",{className:"rounded-md px-3 py-2",style:{background:"var(--mohap-surface)",border:"1px solid var(--mohap-border)"},children:[e.jsx("div",{className:"text-[10px] uppercase tracking-wider font-medium",style:{color:"var(--mohap-text-muted)"},children:t}),e.jsx("div",{className:"text-[18px] font-semibold mt-0.5",style:{color:"var(--mohap-text-primary)"},children:s})]})}const xe="https://n71-mission-worker.fly.dev";function he(){const{workspace:s}=r(),[a,l]=t.useState([]),[d,c]=t.useState(!0),[m,p]=t.useState(!1),[u,x]=t.useState(!1),[h,g]=t.useState(null),[v,y]=t.useState("pending"),j=t.useCallback(async()=>{if(null==s?void 0:s.id){c(!0);try{let e=o.from("evidence_supersedes_proposals").select("proposal_id, old_doc_id, new_doc_id, basis, confidence_score, status, detail, proposed_at, reviewed_at").eq("workspace_id",s.id).order("proposed_at",{ascending:!1}).limit(200);"all"!==v&&(e=e.eq("status",v));const{data:t,error:a}=await e;if(a)throw a;const r=t??[],n=Array.from(new Set(r.flatMap(e=>[e.old_doc_id,e.new_doc_id]).filter(Boolean)));let i=new Map;if(n.length>0){const{data:e}=await o.from("evidence_documents").select("doc_id, title, published_at").in("doc_id",n);for(const t of e??[])i.set(t.doc_id,{title:t.title,published_at:t.published_at})}l(r.map(e=>{var t,s,a,r;return{...e,old_title:(null==(t=i.get(e.old_doc_id))?void 0:t.title)??"(unknown)",new_title:(null==(s=i.get(e.new_doc_id))?void 0:s.title)??"(unknown)",old_published_at:(null==(a=i.get(e.old_doc_id))?void 0:a.published_at)??null,new_published_at:(null==(r=i.get(e.new_doc_id))?void 0:r.published_at)??null}}))}catch(e){n.error(`Failed to load proposals: ${e instanceof Error?e.message:String(e)}`)}finally{c(!1)}}},[null==s?void 0:s.id,v]);t.useEffect(()=>{j()},[j]);const w=t.useCallback(async()=>{if(null==s?void 0:s.id){x(!0);try{const{data:{session:e}}=await o.auth.getSession();if(!(null==e?void 0:e.access_token))throw new Error("not signed in");const t=await fetch(`${xe}/evidence/extract-effective-dates`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${e.access_token}`},body:JSON.stringify({workspace_id:s.id,limit:50})});if(!t.ok)throw new Error(`HTTP ${t.status}`);const a=await t.json(),r=null==a?void 0:a.result;n.success(`Dates refreshed. Scanned ${(null==r?void 0:r.docs_scanned)??0}, updated ${(null==r?void 0:r.docs_updated)??0} (high-confidence: ${(null==r?void 0:r.high_confidence)??0}).`)}catch(e){n.error(`Date refresh failed: ${e instanceof Error?e.message:String(e)}`)}finally{x(!1)}}},[null==s?void 0:s.id]),N=t.useCallback(async()=>{if(null==s?void 0:s.id){p(!0);try{const{data:{session:e}}=await o.auth.getSession();if(!(null==e?void 0:e.access_token))throw new Error("not signed in");const t=await fetch(`${xe}/evidence/detect-supersedes`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${e.access_token}`},body:JSON.stringify({workspace_id:s.id})});if(!t.ok)throw new Error(`HTTP ${t.status}`);const a=await t.json(),r=null==a?void 0:a.result;n.success(`Detector ran. Inserted ${(null==r?void 0:r.proposals_inserted)??0}, auto-applied ${(null==r?void 0:r.proposals_auto_applied)??0}, pending ${(null==r?void 0:r.proposals_pending_review)??0}.`),await j()}catch(e){n.error(`Detector failed: ${e instanceof Error?e.message:String(e)}`)}finally{p(!1)}}},[null==s?void 0:s.id,j]),k=t.useCallback(async e=>
13{if(!h){g(e.proposal_id);try{const{error:t}=await o.from("evidence_documents").update({supersedes:e.old_doc_id}).eq("doc_id",e.new_doc_id);if(t)throw t;const{error:s}=await o.from("evidence_supersedes_proposals").update({status:"human_approved",reviewed_at:(new Date).toISOString()}).eq("proposal_id",e.proposal_id);if(s)throw s;n.success("Approved."),await j()}catch(t){n.error(`Approve failed: ${t instanceof Error?t.message:String(t)}`)}finally{g(null)}}},[h,j]),_=t.useCallback(async e=>{if(!h){g(e.proposal_id);try{const{error:t}=await o.from("evidence_supersedes_proposals").update({status:"rejected",reviewed_at:(new Date).toISOString()}).eq("proposal_id",e.proposal_id);if(t)throw t;n.success("Rejected."),await j()}catch(t){n.error(`Reject failed: ${t instanceof Error?t.message:String(t)}`)}finally{g(null)}}},[h,j]);return t.useMemo(()=>{const e={pending:0,auto_applied:0,rejected:0,all:a.length};for(const t of a)"pending"===t.status?e.pending+=1:"auto_applied"===t.status?e.auto_applied+=1:"rejected"===t.status&&(e.rejected+=1);return e},[a]),e.jsxs("div",{className:"px-6 py-5 space-y-4",children:[e.jsxs("div",{className:"flex items-start justify-between gap-4",children:[e.jsxs("div",{children:[e.jsx("div",{className:"mohap-section-label mb-1",children:"Supersedes review"}),e.jsx("p",{className:"text-[12px] leading-relaxed max-w-2xl",style:{color:"var(--mohap-text-secondary)"},children:"Auto-detected version chains. Rows with confidence above 0.92 are applied automatically; lower-confidence pairs queue here for human approval. Approving stamps the supersedes link; rejecting closes the proposal without touching the document graph."})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs("button",{onClick:w,disabled:u,className:"mohap-button-secondary inline-flex items-center gap-1.5 text-[12px]",title:"Run M31a effective-date extractor over docs missing or low-confidence dates.",children:[u?e.jsx(f,{className:"h-3.5 w-3.5 animate-spin"}):e.jsx(P,{className:"h-3.5 w-3.5"}),"Refresh dates"]}),e.jsxs("button",{onClick:N,disabled:m,className:"mohap-button-secondary inline-flex items-center gap-1.5 text-[12px]",children:[m?e.jsx(f,{className:"h-3.5 w-3.5 animate-spin"}):e.jsx(b,{className:"h-3.5 w-3.5"}),"Run detector"]})]})]}),e.jsx("div",{className:"flex items-center gap-1",children:["pending","auto_applied","rejected","all"].map(t=>e.jsx("button",{onClick:()=>y(t),className:i("px-2.5 py-1 rounded-md text-[11px] font-medium transition"),style:v===t?{background:"var(--mohap-primary-light)",color:"var(--mohap-primary-dark)"}:{color:"var(--mohap-text-secondary)"},children:"pending"===t?"Pending":"auto_applied"===t?"Auto-applied":"rejected"===t?"Rejected":"All"},t))}),d?e.jsxs("div",{className:"py-12 flex items-center justify-center text-[12px]",style:{color:"var(--mohap-text-secondary)"},children:[e.jsx(f,{className:"h-4 w-4 animate-spin mr-2"}),"Loading proposalsâ¦"]}):0===a.length?e.jsxs("div",{className:"py-12 text-center text-[12px]",style:{color:"var(--mohap-text-secondary)"},children:["No proposals match this filter. ","pending"===v&&"Run the detector to populate the queue."]}):e.jsx("div",{className:"rounded-lg border",style:{borderColor:"var(--mohap-border)"},children:a.map((t,s)=>e.jsx(fe,{row:t,isLast:s===a.length-1,busy:h===t.proposal_id,onApprove:()=>k(t),onReject:()=>_(t)},t.proposal_id))})]})}function fe({row:t,isLast:s,busy:a,onApprove:r,onReject:o}){var n,d,c;const m=t.confidence_score,p=m>=.92?"bg-emerald-500/10 text-emerald-400 border-emerald-500/30":m>=.85?"bg-amber-500/10 text-amber-400 border-amber-500/30":"bg-foreground
13/[0.06] text-foreground/55 border-foreground/15",u=null==(n=t.detail)?void 0:n.stem_similarity,x=null==(d=t.detail)?void 0:d.published_gap_days,h=null==(c=t.detail)?void 0:c.shared_section_count,g="pending"===t.status;return e.jsxs("div",{className:i("flex items-start justify-between gap-4 px-4 py-3",!s&&"border-b"),style:{borderColor:"var(--mohap-border)"},children:[e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-1.5",children:[e.jsxs("span",{className:i("inline-flex rounded-full border px-2 py-0.5 text-[10px] font-medium uppercase tracking-wider",p),children:[(100*m).toFixed(0),"%"]}),e.jsxs("span",{className:"text-[10px] uppercase tracking-wider",style:{color:"var(--mohap-text-secondary)"},children:["title_match"===t.basis?"Title match":t.basis,"pending"!==t.status&&` · ${t.status.replace("_"," ")}`]})]}),e.jsxs("div",{className:"text-[13px] leading-snug mb-1",style:{color:"var(--mohap-text-primary)"},children:[e.jsx("span",{className:"opacity-70 line-through decoration-1",children:t.old_title}),e.jsx(U,{className:"inline mx-1.5 h-3 w-3 opacity-50"}),e.jsx("span",{className:"font-medium",children:t.new_title})]}),e.jsxs("div",{className:"flex items-center gap-3 text-[10px]",style:{color:"var(--mohap-text-secondary)"},children:[t.old_published_at&&e.jsxs("span",{children:["old: ",t.old_published_at.slice(0,10)]}),t.new_published_at&&e.jsxs("span",{children:["new: ",t.new_published_at.slice(0,10)]}),"number"==typeof u&&e.jsxs("span",{children:["stem: ",(100*u).toFixed(0),"%"]}),"number"==typeof x&&e.jsxs("span",{children:["gap: ",x,"d"]}),"number"==typeof h&&h>0&&e.jsxs("span",{children:["shared sections: ",h]})]})]}),g&&e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsxs("button",{onClick:r,disabled:a,className:"inline-flex items-center gap-1 px-2 py-1 rounded-md text-[11px] font-medium border transition",style:{borderColor:"var(--mohap-border)",background:"var(--mohap-primary-light)",color:"var(--mohap-primary-dark)"},children:[a?e.jsx(f,{className:"h-3 w-3 animate-spin"}):e.jsx(y,{className:"h-3 w-3"}),"Approve"]}),e.jsxs("button",{onClick:o,disabled:a,className:"inline-flex items-center gap-1 px-2 py-1 rounded-md text-[11px] font-medium border transition",style:{borderColor:"var(--mohap-border)",color:"var(--mohap-text-secondary)"},children:[e.jsx(l,{className:"h-3 w-3"}),"Reject"]})]})]})}const ge=[{id:"memory",label:"Memory",icon:I},{id:"documents",label:"Documents",icon:j},{id:"supersedes",label:"Supersedes",icon:$},{id:"connections",label:"Connections",icon:M},{id:"governance",label:"Governance",icon:R},{id:"audit",label:"Audit",icon:A}];function ve(){const a=s(),{hasView:r,hasWrite:o,role:n,loading:l}=c(),[d,m]=t.useState("documents");if(l)return null;return r("*")||o("*")?e.jsxs("div",{className:"flex flex-col min-h-screen",style:{background:"var(--mohap-surface-secondary)"},children:[e.jsx("header",{className:"flex-shrink-0 flex items-center justify-between gap-4 px-6 py-3 border-b",style:{borderColor:"var(--mohap-border)",background:"var(--mohap-surface)"},children:e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsxs("button",{onClick:()=>a("/mohap"),className:"flex items-center gap-1.5 text-[13px] hover:opacity-80",style:{color:"var(--mohap-text-secondary)"},children:[e.jsx(O,{className:"h-3.5 w-3.5"}),"Back to chat"]}),e.jsx("div",{className:"w-px h-5",style:{background:"var(--mohap-border)"}}),e.jsx("h1",{className:"text-[15px] font-semibold",style:{color:"var(--mohap-text-primary)"},children:"Admin · Connect space"})]})}),e.jsx("div",{className:"flex-shrink-0 flex items-center gap-1 px-6 py-2 border-b",style:{borderColor:"var(--mohap-border)",background:"var(--mohap-surface)"},children:ge.map(t=>{const s=t.icon;return e.jsxs("button",{onClick:()=>m(t.id),className:i("flex items-center gap-1.5 px-3 py-1.5 text-[12px] font-medium rounded-md transition"),style:d===t.id?{background:"var(--mohap-primary-light)",color:"var(--mohap-primary-dark)"}:{color:"var(--mohap-text-secondary)"},children:[e.jsx(s,{className:"h-3.5 w-3.5"}),t.label]},t.id)})}),e.jsxs("main",{className:"flex-1 min-h-0 overflow-y-auto",children:["memory"===d&&e.jsx(pe,{}),"documents"===d&&e.jsx(Z,{}),"supersedes"===d&&e.jsx(he,{}),"connections"===d&&e.jsx(re,{}),"governance"===d&&e.jsx(ne,{}),"audit"===d&&e.jsx(ie,{})]})]}):e.jsx("div",{className:"flex min-h-screen items-center justify-center px-6",children:e.jsxs("div",{className:"max-w-md text-center",children:[e.jsx("div",{className:"mohap-section-label mb-2",children:"Admin only"}),e.jsxs("p",{className:"text-sm leading-relaxed mb-4",style:{color:"var(--mohap-text-secondary)"},children:["This area is restricted to system administrators. Your role is ",e.jsx("strong",{children:(null==n?void 0:n.role_label)??"â"}),"."]}),e.jsx("button",{onClick:()=>a("/mohap"),className:"mohap-button-primary",children:"Back to chat"})]})})}export{ve as MinistryAdmin}; 14//# sourceMappingURL=MinistryAdmin-DgqIGZDg.js.map
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.