PageSourceSearch

https://argro.ai/assets/CentroOperativo-Cz_5027V.js

js argro.ai collected 2026-10-05 13:49:28 UTC 82,773 bytes, 1 lines download raw bytes

1import{D as Re,a as ie,b as ds,r as p,s as se,j as e,L as te,_ as ms,X as Le,u as Pe,t as ae,T as xs,E as Ne,F as _e,G as we,c as ps}from"./index-gpB4H7P-.js";import{C as re,d as W}from"./card-UEmT7wX_.js";import{B as C}from"./button-BF_pI_cx.js";import{B as F}from"./badge-DVcRYu5G.js";import{S as us}from"./SanidadCampoEmbed-qG-ur_Rr.js";import{I as K}from"./input-DqilqiNh.js";import{S as Y,a as J,b as X,c as Z,d as k,C as hs}from"./select-DQXnM0cA.js";import{c as Oe,H as ke}from"./clasificar-cc-2AanI5Ow.js";import{P as fe}from"./plus-DSFwzlKO.js";import{L as oe}from"./loader-circle-BZn5kwlm.js";import{T as me}from"./triangle-alert-SezU0PVV.js";import{T as gs}from"./trending-up-DUPfHyyo.js";import{T as fs}from"./trending-down-Dibtsbzx.js";import{A as be}from"./arrow-right-C7TQlL4i.js";import{C as Me}from"./chevron-down-iUZYC0uS.js";import{A as js,a as vs,b as bs,c as Ns,d as _s,e as ws,f as Cs,g as ys}from"./alert-dialog-Z48jzhGf.js";import{T as ze,u as Ss,a as Qe,b as ks,c as Ae,C as Ps}from"./resolve-mode-0wbZ70VR.js";import{S as Es,a as Ts,b as Ds,c as As,d as Fs}from"./sheet-CAcnJQf_.js";import{L as V}from"./label-DvkWbrYH.js";import{T as $s}from"./textarea-B9fZZqNe.js";import{S as Is}from"./switch-wSKguWqw.js";import{P as Rs,a as Ls,b as Ms}from"./popover-VWP5p5eQ.js";import{a as zs}from"./store-BFEKDr4O.js";import{S as es}from"./search-CJmA_OXi.js";import{P as Fe}from"./package-B0tNWy7r.js";import{A as ss}from"./activity-BcqSsasY.js";import{C as Vs}from"./calendar-OSiu9dd1.js";import{S as Os}from"./save-CWIyOfit.js";import{D as Us,a as Bs,b as Hs,c as qs,d as Gs,f as Ws}from"./dialog-D3Ts-esm.js";import{S as Ks}from"./separator-5OrNIgQz.js";import{T as Ys,a as Js,b as Ue,c as ue,d as Xs,e as he}from"./table-C1CTdPme.js";import{u as Zs}from"./useExcelImport-D0akkfi-.js";import{F as Be}from"./file-spreadsheet-BEwEI5ns.js";import{C as $e}from"./circle-check-D5CTUKxt.js";import{C as Ve}from"./chevron-right-BbcC-mYO.js";import{U as ts}from"./upload-NuEIBDdl.js";import{C as Qs}from"./chevron-left-BSneG0T2.js";import{D as et}from"./download-_hfmVGpj.js";import{F as st}from"./filter-bQuN4CgF.js";import{S as Ie}from"./stethoscope-HLTCdAJj.js";import{P as tt}from"./pen-line-cE1eYRM_.js";import{C as at}from"./copy-CuMAynh5.js";import{P as rt}from"./power-Dvs4ovh2.js";import{T as as}from"./trash-2-BZO9a3Cb.js";import ot from"./DashboardAnalisisEngorde-cZaxWj3c.js";import{u as it,s as ct,l as nt,a as lt}from"./data-supabase-hF0vl9oU.js";import{T as dt,a as mt,S as xt,E as pt,P as ut}from"./mock-D2HhHG2b.js";import{C as He}from"./compass-Bi9zl1SR.js";import{A as ht}from"./arrow-left-CJAueO1C.js";import{B as qe}from"./book-open-CXAw2itp.js";import{C as gt}from"./chart-column-CHKZ2bUb.js";import{S as ve}from"./sparkles-oBCHPLP5.js";import{T as ft}from"./target-DcEuAr8N.js";import{C as jt}from"./circle-alert-DyWyNULz.js";import{D as vt}from"./database-Cxd9fBnI.js";import{Z as bt}from"./zap-3Bo2pA-z.js";import"./clock-BzC8nxgW.js";import"./layers-BonXBZXw.js";import"./index-BdQq_4o_.js";import"./index-DYADRlsT.js";import"./index-BrxAtw8T.js";import"./index-DwfZcdIj.js";import"./check-BYQ1WMQj.js";import"./index-gXATfCt0.js";import"./useQuery-DZqRJRpe.js";import"./useDataOwnerId-CZbLSmKC.js";import"./useAuditLog-CRka8RB9.js";import"./calendar-DoJyCO1_.js";import"./isSameDay-BqGqykU8.js";import"./format-DQ2CmAN1.js";import"./en-US-B19iUWR5.js";import"./addDays-6QIOBaFG.js";import"./differenceInCalendarMonths-I4vhmA7h.js";import"./isBefore-CX1EHamI.js";import"./startOfMonth-DU7PqccR.js";import"./setMonth-Hublrn4T.js";import"./endOfMonth-CHaC4cNo.js";import"./FeatureGate-DpJvgIEd.js";import"./lock-D_GTxaTG.js";import"./ticket-d7nAEa7S.js";import"./wheat-K_nRg3wR.js";import"./crown-DD70c80D.js";import"./building-2-CBZRhfi8.js";import"./dollar-sign-1I9pU1lc.js";import"./generateCategoricalChart-BBMJb9At.js";import"./LineChart-Di5VUyF9.js";import"./scale-U0IMNV47.js";import"./differenceInDays-Bh5JpfNg.js";import"./animal-display-Dc40ph0q.js";import"./circle-Jcte22uh.js";const Te={optimo:"bg-emerald-500/10 text-emerald-600 border-emerald-500/40",bajo:"bg-amber-500/10 text-amber-600 border-amber-500/40",alto:"bg-blue-500/10 text-blue-600 border-blue-500/40",critico:"bg-red-500/10 text-red-600 border-red-500/40"},Ce=a=>new Date(a).toLocaleDateString("es-AR",{day:"2-digit",month:"short",year:"numeric"}),Nt=a=>Math.floor((new Date().getTime()-new Date(a).getTime())/864e5),_t=({refreshKey:a=0}
1)=>{const{activeEstablecimientoId:l}=Re(),{t}=ie(),h=ds(),[i,x]=p.useState([]),[d,s]=p.useState([]),[b,R]=p.useState([]),[$,D]=p.useState(!0),[L,M]=p.useState(0);p.useEffect(()=>{l&&(D(!0),(async()=>{const[r,m,j]=await Promise.all([se.from("condicion_corporal_evaluaciones").select("id, rodeo_id, categoria, fecha_evaluacion, escala_usada, cc_promedio, cantidad_animales_evaluados, peso_promedio_kg, biotipo, momento_productivo, observaciones, accion_recomendada").eq("establecimiento_id",l).order("fecha_evaluacion",{ascending:!1}),se.from("rodeos").select("id, nombre, cantidad_total").eq("establecimiento_id",l),se.from("procesos_productivos").select("id, nombre, rodeos_ids").eq("establecimiento_id",l)]);x(r.data??[]),s(m.data??[]),R(j.data??[]),D(!1)})())},[l,a,L]);const g=p.useMemo(()=>{const r=new Map;for(const m of d)r.set(m.id,m);return r},[d]),w=p.useMemo(()=>{const r=new Map;for(const m of b)for(const j of m.rodeos_ids??[])r.has(j)||r.set(j,m);return r},[b]),[c,N]=p.useState(""),[ce,A]=p.useState("todas"),[B,H]=p.useState("todos"),[O,ne]=p.useState("todas"),E=p.useMemo(()=>{const r=new Set;for(const m of i)r.add(m.categoria);return Array.from(r).sort()},[i]),U=p.useMemo(()=>i.map(r=>({ev:r,clasif:Oe(Number(r.cc_promedio),r.categoria,r.momento_productivo??"general",r.biotipo??void 0)})),[i]),Q=p.useMemo(()=>U.filter(({ev:r,clasif:m})=>{var j;if(ce!=="todas"&&r.categoria!==ce||B!=="todos"&&r.momento_productivo!==B||O!=="todas"&&m.clasificacion!==O)return!1;if(c.trim()){const v=c.toLowerCase();if(!(((j=g.get(r.rodeo_id??""))==null?void 0:j.nombre)??"").toLowerCase().includes(v)&&!r.categoria.toLowerCase().includes(v))return!1}return!0}),[U,ce,B,O,c,g]),I=p.useMemo(()=>{const r=new Set,m=[];for(const j of U){const v=j.ev.rodeo_id;!v||r.has(v)||(r.add(v),m.push(j))}return m},[U]),z=p.useMemo(()=>I.filter(({clasif:r})=>r.clasificacion==="bajo"||r.clasificacion==="critico"),[I]),f=p.useMemo(()=>{var j;const r=I.length>0?I.reduce((v,S)=>v+Number(S.ev.cc_promedio),0)/I.length:0,m=((j=i[0])==null?void 0:j.fecha_evaluacion)??null;return{ccPromedio:Math.round(r*10)/10,rodeosBajo:z.length,ultimaFecha:m,total:i.length}},[i,I,z]),y=p.useMemo(()=>{const r=new Map;for(const j of i)j.rodeo_id&&(r.has(j.rodeo_id)||r.set(j.rodeo_id,[]),r.get(j.rodeo_id).push(j));const m=new Map;for(const[j,v]of r.entries()){if(v.length<2){m.set(j,"estable");continue}const S=Number(v[0].cc_promedio)-Number(v[1].cc_promedio);m.set(j,S>.2?"mejorando":S<-.2?"empeorando":"estable")}return m},[i]),[_,q]=p.useState(!1),n=p.useMemo(()=>{const r=new Map;for(const m of i){const j=m.rodeo_id??"__sin_rodeo__";r.has(j)||r.set(j,[]),r.get(j).push(m)}return Array.from(r.entries()).sort((m,j)=>{var G,xe;const v=m[0]==="__sin_rodeo__"?"Sin rodeo":((G=g.get(m[0]))==null?void 0:G.nombre)??"Rodeo",S=j[0]==="__sin_rodeo__"?"Sin rodeo":((xe=g.get(j[0]))==null?void 0:xe.nombre)??"Rodeo";return v.localeCompare(S)})},[i,g]),o=r=>{if(r){const m=w.get(r);if(m){h(`/dashboard/proceso-productivo/cc-sesion?proceso=${m.id}`);return}}h("/dashboard/proceso-productivo/cc-sesion")};return e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"grid grid-cols-2 sm:grid-cols-4 gap-3",children:[e.jsxs("div",{className:"rounded-md border border-border p-3 bg-muted/10",children:[e.jsx("p",{className:"text-[10px] uppercase tracking-wider text-muted-foreground",children:t.procesoCC.campo.kpiCCProm}),e.jsx("p",{className:"text-2xl font-bold text-foreground",children:f.ccPromedio||"—"}),e.jsx("p",{className:"text-[10px] text-muted-foreground",children:t.procesoCC.campo.kpiCCPromHint})]}),e.jsxs("div",{className:`rounded-md border p-3 ${f.rodeosBajo>0?"border-amber-500/40 bg-amber-500/5":"border-emerald-500/40 bg-emerald-500/5"}`,children:[e.jsx("p",{className:"text-[10px] uppercase tracking-wider text-muted-foreground",children:t.procesoCC.campo.kpiRodeosBajo}),e.jsx("p",{className:`text-2xl font-bold ${f.rodeosBajo>0?"text-amber-600":"text-emerald-600"}`,children:f.rodeosBajo}),e.jsx("p",{className:"text-[10px] text-muted-foreground",children:(I.length===1?t.procesoCC.campo.kpiRodeosBajoHintOne:t.procesoCC.campo.kpiRodeosBajoHintMany).replace("{n}",String(I.length))})]}),e.jsxs("div",{className:"rounded-md border border-border p-3 bg-muted/10",children:[e.jsx("p",{className:"text-[10px] uppercase tracking-wider text-muted-foreground",children:t.procesoCC.campo.kpiUltimaEval}),e.jsx("p",{className:"text-2xl font-bold text-foreground",children:f.ultimaFecha?t.procesoCC.campo.kpiUltimaEvalDaysAgo.replace("{n}",String(Nt(f.ultimaFecha))):"—"}),e.jsx("p",{className:"text-[10px] text-muted-foreground",children:f.ultimaFecha?Ce(f.ultimaFecha):t.procesoCC.campo.kpiNoRecords})]}),e.jsxs("div",{className:"rounded-md border border-border p-3 bg-muted/10",children:[e.jsx("p",{className:"text-[10px] uppercase tracking-wider text-muted-foreground",children:t.procesoCC.campo.kpiTotal}),e.jsx("p",{className:"text-2xl font-bold text-foreground",children:f.total}),e.jsx("p",{className:"text-[10px] text-muted-foreground",children:t.procesoCC.campo.kpiTotalHint})]})]}),e.jsxs("div",{className:"flex flex-col sm:flex-row gap-2 sm:items-center justify-between",children:[e.jsx("p",{className:"text-xs text-muted-foreground",children:t.procesoCC.campo.ctaSubtitle}),e.jsxs(C,{size:"sm",onClick:()=>o(void 0),children:[e.jsx(fe,{className:"h-3.5 w-3.5 mr-1"}),t.procesoCC.campo.loadEvaluation]})]}),e.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-4 gap-2",children:[e.jsx(K,{placeholder:t.procesoCC.campo.searchPlaceholder,value:c,onChange:r=>N(r.target.value),className:"h-9 text-sm"}),e.jsxs(Y,{value:ce,onValueChange:A,children:[e.jsx(J,{className:"h-9 text-sm",children:e.jsx(X,{placeholder:t.procesoCC.campo.categoriaPlaceholder})}),e.jsxs(Z,{children:[e.jsx(k,{value:"todas",children:t.procesoCC.campo.allCategories}),E.map(r=>e.jsx(k,{value:r,children:r},r))]})]}),e.jsxs(Y,{value:B,onValueChange:H,children:[e.jsx(J,{className:"h-9 text-sm",children:e.jsx(X,{placeholder:t.procesoCC.campo.momentoPlaceholder})}),e.jsxs(Z,{children:[e.jsx(k,{value:"todos",children:t.procesoCC.campo.allMomentos}),e.jsx(k,{value:"general",children:t.procesoCC.momentos.general}),e.jsx(k,{value:"pre_servicio",children:t.procesoCC.momentos.pre_servicio}),e.jsx(k,{value:"preparto",children:t.procesoCC.momentos.preparto}),e.jsx(k,{value:"post_parto",children:t.procesoCC.momentos.post_parto}),e.jsx(k,{value:"destete",children:t.procesoCC.momentos.destete}),e.jsx(k,{value:"salida_terminacion",children:t.procesoCC.momentos.salida_terminacion})]})]}),e.jsxs(Y,{value:O,onValueChange:ne,children:[e.jsx(J,{className:"h-9 text-sm",children:e.jsx(X,{placeholder:t.procesoCC.campo.estadoPlaceholder})}),e.jsxs(Z,{children:[e.jsx(k,{value:"todas",children:t.procesoCC.campo.allEstados}),e.jsx(k,{value:"optimo",children:t.procesoCC.clasif.optimo}),e.jsx(k,{value:"bajo",children:t.procesoCC.clasif.bajo}),e.jsx(k,{value:"alto",children:t.procesoCC.clasif.alto}),e.jsx(k,{value:"critico",children:t.procesoCC.clasif.critico})]})]})]}),$?e.jsxs("div",{className:"flex items-center gap-2 text-xs text-muted-foreground py-6 justify-center",children:[e.jsx(oe,{className:"h-3.5 w-3.5 animate-spin"})," ",t.procesoCC.campo.loadingEvals]}):i.length===0?e.jsxs("div",{className:"rounded-md border border-dashed border-muted-foreground
1/30 p-6 text-center space-y-2",children:[e.jsx(ke,{className:"h-10 w-10 text-muted-foreground/40 mx-auto"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:t.procesoCC.campo.emptyNoEvals}),e.jsxs(C,{size:"sm",onClick:()=>o(void 0),children:[e.jsx(fe,{className:"h-3.5 w-3.5 mr-1"}),t.procesoCC.campo.loadFirstEvaluation]})]}):e.jsxs(e.Fragment,{children:[z.length>0&&e.jsxs("div",{className:"space-y-2",children:[e.jsxs("h4",{className:"text-xs font-bold uppercase tracking-wider flex items-center gap-1.5 text-amber-600",children:[e.jsx(me,{className:"h-3 w-3"}),t.procesoCC.campo.bucketBajoObjetivo,e.jsx(F,{variant:"outline",className:"text-[10px]",children:z.length})]}),e.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-2",children:z.map(({ev:r,clasif:m})=>{const j=g.get(r.rodeo_id??""),v=r.rodeo_id?w.get(r.rodeo_id):null,S=r.rodeo_id?y.get(r.rodeo_id)??"estable":"estable";return e.jsxs("div",{className:`rounded-md border p-3 space-y-1.5 ${m.clasificacion==="critico"?"border-red-500/40 bg-red-500/5":"border-amber-500/40 bg-amber-500/5"}`,children:[e.jsxs("div",{className:"flex items-center justify-between gap-2",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsx("p",{className:"text-sm font-semibold truncate",children:(j==null?void 0:j.nombre)??t.procesoCC.campo.herdNoName}),e.jsxs("p",{className:"text-[11px] text-muted-foreground",children:[r.categoria,r.momento_productivo&&r.momento_productivo!=="general"&&` · ${t.procesoCC.momentos[r.momento_productivo]??r.momento_productivo.replace(/_/g," ")}`," · ",r.cantidad_animales_evaluados," ",t.procesoCC.campo.headEvalShort]})]}),e.jsxs(F,{variant:"outline",className:`text-[10px] ${Te[m.clasificacion]}`,children:["CC ",r.cc_promedio," · ",t.procesoCC.clasif[m.clasificacion]]})]}),m.accionKey&&e.jsx("p",{className:"text-[11px] text-muted-foreground italic",children:t.validation.cc.accion[m.accionKey]??m.accion}),e.jsxs("div",{className:"flex items-center justify-between gap-2 pt-1 border-t border-border/60",children:[e.jsxs("span",{className:"text-[10px] text-muted-foreground flex items-center gap-1",children:[S==="mejorando"&&e.jsxs(e.Fragment,{children:[e.jsx(gs,{className:"h-3 w-3 text-emerald-600"})," ",t.procesoCC.campo.trendUp]}),S==="empeorando"&&e.jsxs(e.Fragment,{children:[e.jsx(fs,{className:"h-3 w-3 text-red-600"})," ",t.procesoCC.campo.trendDown]}),S==="estable"&&e.jsx(e.Fragment,{children:t.procesoCC.campo.trendStable})," · ",Ce(r.fecha_evaluacion)]}),e.jsxs("div",{className:"flex items-center gap-1",children:[r.rodeo_id&&e.jsx(C,{size:"sm",variant:"outline",className:"h-7 text-[10px] px-2",onClick:()=>o(r.rodeo_id),children:t.procesoCC.campo.newEvalShort}),v&&e.jsx(te,{to:`/dashboard/proceso-productivo/procesos/${v.id}?tab=cc`,className:"text-primary hover:text-primary/80",title:t.procesoCC.campo.seeTrend,children:e.jsx(be,{className:"h-4 w-4"})})]})]})]},r.id)})})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs("h4",{className:"text-xs font-bold uppercase tracking-wider flex items-center gap-1.5 text-foreground",children:[t.procesoCC.campo.lastEvals,e.jsx(F,{variant:"outline",className:"text-[10px]",children:Q.length})]}),Q.length===0?e.jsx("p",{className:"text-sm text-muted-foreground italic text-center py-4",children:t.procesoCC.campo.noMatch}):e.jsxs("div",{className:"divide-y divide-border border border-border rounded-md",children:[Q.slice(0,50).map(({ev:r,clasif:m})=>{const j=r.rodeo_id?g.get(r.rodeo_id):null,v=r.rodeo_id?w.get(r.rodeo_id):null;return e.jsxs("div",{className:"p-3 flex items-start gap-3",children:[e.jsx("div",{className:`h-9 w-9 rounded-md flex items-center justify-center text-sm font-bold shrink-0 ${Te[m.clasificacion]}`,children:r.cc_promedio}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[e.jsx("p",{className:"text-sm font-medium text-foreground",children:(j==null?void 0:j.nombre)??t.procesoCC.campo.noHerd}),e.jsx(F,{variant:"outline",className:"text-[10px]",children:r.categoria}),e.jsx(F,{variant:"outline",className:`text-[10px] ${Te[m.clasificacion]}`,children:t.procesoCC.clasif[m.clasificacion]})]}),e.jsxs("p",{className:"text-[11px] text-muted-foreground",children:[Ce(r.fecha_evaluacion)," · ",r.cantidad_animales_evaluados," ",t.procesoCC.campo.headShort,r.peso_promedio_kg&&` · ${r.peso_promedio_kg} kg ${t.procesoCC.campo.avgShort}`,r.momento_productivo&&r.momento_productivo!=="general"&&` · ${t.procesoCC.momentos[r.momento_productivo]??r.momento_productivo.replace(/_/g," ")}`]}),r.accion_recomendada&&e.jsx("p",{className:"text-[11px] text-muted-foreground italic mt-0.5",children:r.accion_recomendada})]}),v&&e.jsx(te,{to:`/dashboard/proceso-productivo/procesos/${v.id}?tab=cc`,className:"text-primary hover:text-primary/80 shrink-0 mt-1",title:t.procesoCC.campo.seeTrend,children:e.jsx(be,{className:"h-4 w-4"})})]},r.id)}),Q.length>50&&e.jsx("p",{className:"text-[11px] text-muted-foreground italic px-3 py-2",children:t.procesoCC.campo.moreEvalsA.replace("{n}",String(Q.length-50))})]})]}),e.jsxs("div",{className:"border border-border rounded-md",children:[e.jsxs("button",{type:"button",onClick:()=>q(r=>!r),className:"w-full flex items-center justify-between p-3 hover:bg-muted/30 transition-colors",children:[e.jsxs("span",{className:"text-sm font-semibold flex items-center gap-2",children:[e.jsx(ke,{className:"h-4 w-4 text-primary"}),t.procesoCC.campo.porRodeo,e.jsx(F,{variant:"outline",className:"text-[10px]",children:n.length})]}),_?e.jsx(hs,{className:"h-4 w-4"}):e.jsx(Me,{className:"h-4 w-4"})]}),_&&e.jsx("div",{className:"border-t border-border p-3 space-y-3",children:n.map(([r,m])=>{var v;const j=r==="__sin_rodeo__"?t.procesoCC.campo.sinRodeoAsociado:((v=g.get(r))==null?void 0:v.nombre)??t.procesoCC.campo.herdNoName;return e.jsxs("div",{children:[e.jsxs("p",{className:"text-xs font-semibold text-foreground mb-1.5",children:[j," ",e.jsxs("span",{className:"text-muted-foreground font-normal",children:["· ",(m.length===1?t.procesoCC.campo.evalCountOne:t.procesoCC.campo.evalCountMany).replace("{n}",String(m.length))]})]}),e.jsx("div",{className:"flex items-end gap-1 h-16 border-b border-l border-border pl-2 pb-1",children:m.slice().reverse().slice(-12).map(S=>{const G=S.escala_usada==="1_9"?9:5,xe=Number(S.cc_promedio)/G*100,je=Oe(Number(S.cc_promedio),S.categoria,S.momento_productivo??"general",S.biotipo??void 0),Ee=je.clasificacion==="critico"?"bg-red-500":je.clasificacion==="bajo"?"bg-amber-500":je.clasificacion==="alto"?"bg-blue-500":"bg-emerald-500";return e.jsxs("div",{className:"flex-1 flex flex-col items-center gap-0.5",children:[e.jsx("span",{className:"text-[8px] text-muted-foreground",children:S.cc_promedio}),e.jsx("div",{className:`w-full rounded-t ${Ee} transition-all`,style:{height:`${xe}%`,minHeight:"6px"},title:`${Ce(S.fecha_evaluacion)}: CC ${S.cc_promedio}`})]},S.id)})})]},r)})})]})]})]})},wt=new Set(["Vaca","Toro","Toro capón","Vaquillona","Novillo","Novillito","Ternera","Ternero","Vaquillona Recría","Novillito Recría"]),Ct=new Set(["nacimiento","pre_servicio","preparto","post_parto","tacto","pre_destete","destete","ingreso_corral","recria","terminacion","engorde","anual"]),Ge=new Set(ze),De=["categoria_animal","etapa_productiva","nombre_protocolo","descripcion","tipo_protocolo","frecuencia_dias","obligatorio","senasa","condicional","activo","articulo_sku","articulo_nombre","dosis","unidad","observaciones"],yt={categoria_animal:"Novillito",etapa_productiva:"recria",nombre_protocolo:"Carbunclo",descripcion:"Si tu zona es endémica de carbunclo, vacuna anual.",tipo_protocolo:"vacuna",fre
1cuencia_dias:365,obligatorio:"sí",senasa:"no",condicional:"sí",activo:"sí",articulo_sku:"VAC-CARB-001",articulo_nombre:"Vacuna Carbunclo",dosis:1,unidad:"dosis",observaciones:"Aplicar según indicación veterinaria"};function ye(a){if(a===!0)return!0;if(a===!1||a==null)return!1;if(typeof a=="number")return a!==0;const l=String(a).trim().toLowerCase();return l?["sí","si","true","1","x","yes","y","verdadero"].includes(l):!1}function We(a){if(a==null)return null;if(typeof a=="number")return Number.isFinite(a)?a:NaN;const l=String(a).trim();if(!l)return null;let t=l.replace(/[^\d.,-]/g,"");const h=t.includes(","),i=t.includes(".");if(h&&i){const d=t.lastIndexOf(","),s=t.lastIndexOf(".");d>s?t=t.replace(/\./g,"").replace(",","."):t=t.replace(/,/g,"")}else h&&(t=t.replace(/\./g,"").replace(",","."));const x=parseFloat(t);return Number.isFinite(x)?x:NaN}const le=a=>a==null?"":String(a).trim();function St(a,l){const t=l+2,h=a.activo,i=h==null||String(h).trim()==="";return{rowIndex:t,raw:a,categoria_animal:le(a.categoria_animal),etapa_productiva:le(a.etapa_productiva),nombre_protocolo:le(a.nombre_protocolo),descripcion:le(a.descripcion),tipo_protocolo:le(a.tipo_protocolo).toLowerCase(),frecuencia_dias:We(a.frecuencia_dias),obligatorio:ye(a.obligatorio),senasa:ye(a.senasa),condicional:ye(a.condicional),activo:i?!0:ye(h),articulo_sku:le(a.articulo_sku),articulo_nombre:le(a.articulo_nombre),dosis:We(a.dosis),unidad:le(a.unidad),observaciones:le(a.observaciones),accion:"error",warnings:[],errores:[],protocoloExistenteId:null,articuloMatchId:null}}const Ke=(a,l,t)=>`${a.trim().toLowerCase()}|${l.trim().toLowerCase()}|${t.trim().toLowerCase()}`;function kt(a,l){const t=new Map;for(const h of l.protocolosExistentes)t.set(Ke(h.categoria,h.etapa,h.nombre_protocolo),h.id);return a.map(h=>{const i={...h,warnings:[],errores:[]};if(i.nombre_protocolo||i.errores.push("Falta nombre_protocolo"),i.categoria_animal||i.errores.push("Falta categoria_animal"),i.etapa_productiva||i.errores.push("Falta etapa_productiva"),i.tipo_protocolo?Ge.has(i.tipo_protocolo)||i.errores.push(`tipo_protocolo inválido: "${i.tipo_protocolo}" (válidos: ${[...Ge].join(", ")})`):i.errores.push("Falta tipo_protocolo"),i.frecuencia_dias!=null&&(Number.isNaN(i.frecuencia_dias)||i.frecuencia_dias<0)&&i.errores.push("frecuencia_dias debe ser número positivo o vacío"),i.categoria_animal&&!wt.has(i.categoria_animal)&&i.warnings.push(`Categoría nueva (no estaba en el catálogo): "${i.categoria_animal}"`),i.etapa_productiva&&!Ct.has(i.etapa_productiva)&&i.warnings.push(`Etapa nueva (no estaba en el catálogo): "${i.etapa_productiva}"`),!i.articulo_sku)(i.articulo_nombre||i.dosis!=null)&&i.warnings.push("SKU vacío: el protocolo se importa sin artículo vinculado");else{const x=l.articulosPorSku.get(i.articulo_sku.trim().toUpperCase());x?i.articuloMatchId=x:i.warnings.push(`Artículo no encontrado (SKU "${i.articulo_sku}"): el protocolo se importa sin vincularlo`)}if(i.errores.length===0){const x=t.get(Ke(i.categoria_animal,i.etapa_productiva,i.nombre_protocolo));x?(i.protocoloExistenteId=x,i.accion="actualizar"):i.accion="crear"}else i.accion="error";return i})}function Pt(a){let l=0,t=0,h=0,i=0;for(const x of a)x.accion==="crear"?l++:x.accion==="actualizar"?t++:h++,x.warnings.length>0&&i++;return{total:a.length,nuevos:l,actualizados:t,errores:h,conWarnings:i}}async function Et(){const a=await ms(()=>import("./xlsx-B6sNpj_1.js"),[]),l={};for(const d of De)l[d]=yt[d]??"";const t=a.utils.json_to_sheet([l],{header:De}),h={categoria_animal:18,etapa_productiva:18,nombre_protocolo:28,descripcion:40,tipo_protocolo:16,frecuencia_dias:14,obligatorio:10,senasa:8,condicional:11,activo:8,articulo_sku:16,articulo_nombre:24,dosis:8,unidad:10,observaciones:36};t["!cols"]=De.map(d=>({wch:h[d]}));const i=a.utils.book_new();a.utils.book_append_sheet(i,t,"Protocolos");const x=new Date().toISOString().slice(0,10);a.writeFile(i,`plantilla_protocolos_${x}.xlsx`)}function Tt(a){return{categoria:a.categoria_animal,etapa:a.etapa_productiva,nombre_protocolo:a.nombre_protocolo,descripcion:a.descripcion||null,tipo_protocolo:a.tipo_protocolo,frecuencia_dias:a.frecuencia_dias,obligatorio_senasa:a.senasa||a.obligatorio,condicional:a.condicional?{if:"manual"}:null,activo:a.activo,dias_previos_evento:0,evento_referencia:Dt(a.etapa_productiva),producto_tipo:At(a.tipo_protocolo),dosis_descripcion:a.dosis!=null&&a.unidad?`${a.dosis} ${a.unidad}`:a.dosis!=null?String(a.dosis):null}}function Dt(a){const l=a.toLowerCase();return l.includes("servicio")?"servicio":l.includes("parto")?"parto":l.includes("destete")?"destete":l==="nacim
1iento"?"nacimiento":l.includes("corral")?"ingreso_corral":l==="recria"?"recria":l==="engorde"||l==="terminacion"?"engorde":"anual"}function At(a){switch(a){case"vacuna":return"vacuna";case"antiparasitario":return"antiparasitario";case"suplementacion":return"suplemento";case"mineralizacion":return"mineral";default:return a}}const Ft=({items:a,onChange:l,readOnly:t})=>{const{articulos:h}=zs(),{t:i}=ie(),x=i.procesoSanidad.articles,[d,s]=p.useState(!1),[b,R]=p.useState(""),$=p.useMemo(()=>{const g=b.trim().toLowerCase(),w=new Set(a.map(c=>c.articulo_id));return h.filter(c=>c.activo).filter(c=>!w.has(c.id)).filter(c=>g?(c.nombre+" "+c.sku).toLowerCase().includes(g):!0).slice(0,30)},[h,a,b]),D=g=>{const w=h.find(c=>c.id===g);w&&(l([...a,{articulo_id:g,articulo_nombre:w.nombre,articulo_sku:w.sku,articulo_activo:w.activo,dosis:null,unidad:w.unidad_base??null,observaciones:null}]),s(!1),R(""))},L=g=>{const w=[...a];w.splice(g,1),l(w)},M=(g,w)=>{const c=[...a];c[g]={...c[g],...w},l(c)};return e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(V,{className:"text-xs",children:x.label}),!t&&e.jsxs(Rs,{open:d,onOpenChange:s,children:[e.jsx(Ls,{asChild:!0,children:e.jsxs(C,{size:"sm",variant:"outline",className:"h-7 text-xs",children:[e.jsx(fe,{className:"h-3 w-3 mr-1"})," ",x.addArticle]})}),e.jsx(Ms,{className:"w-80 p-2",align:"end",children:e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"relative",children:[e.jsx(es,{className:"absolute left-2 top-1/2 -translate-y-1/2 h-3.5 w-3.5 text-muted-foreground"}),e.jsx(K,{autoFocus:!0,placeholder:x.searchPlaceholder,value:b,onChange:g=>R(g.target.value),className:"pl-7 h-8 text-xs"})]}),e.jsx("div",{className:"max-h-64 overflow-y-auto space-y-1",children:$.length===0?e.jsx("p",{className:"text-xs text-muted-foreground text-center py-4",children:h.length===0?x.emptyMaster:x.noResults}):$.map(g=>e.jsxs("button",{type:"button",onClick:()=>D(g.id),className:"w-full flex items-center gap-2 rounded-md px-2 py-1.5 text-left text-xs hover:bg-muted/60 transition-colors",children:[e.jsx(Fe,{className:"h-3 w-3 text-muted-foreground shrink-0"}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("p",{className:"font-medium truncate",children:g.nombre}),g.sku&&e.jsx("p",{className:"text-[10px] text-muted-foreground font-mono",children:g.sku})]})]},g.id))})]})})]})]}),a.length===0?e.jsxs("p",{className:"text-xs text-muted-foreground italic px-2 py-3 border border-dashed border-border rounded-md text-center",children:[x.noneLinkedPre," ",!t&&x.noneLinkedHint]}):e.jsx("div",{className:"space-y-1.5",children:a.map((g,w)=>e.jsxs("div",{className:"rounded-md border border-border bg-card p-2 space-y-1.5",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Fe,{className:"h-3.5 w-3.5 text-muted-foreground shrink-0"}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("p",{className:"text-sm font-medium truncate",children:g.articulo_nombre??x.articleFallback}),e.jsxs("div",{className:"flex items-center gap-1.5 flex-wrap",children:[g.articulo_sku&&e.jsx("span",{className:"text-[10px] text-muted-foreground font-mono",children:g.articulo_sku}),g.articulo_activo===!1&&e.jsxs(F,{variant:"outline",className:"text-[9px] bg-amber-500/10 text-amber-700 dark:text-amber-400 border-amber-500/40",children:[e.jsx(me,{className:"h-2.5 w-2.5 mr-0.5"}),x.inactiveInMaster]})]})]}),!t&&e.jsx(C,{size:"icon",variant:"ghost",className:"h-6 w-6 text-muted-foreground hover:text-destructive",onClick:()=>L(w),title:x.remove,children:e.jsx(Le,{className:"h-3 w-3"})})]}),e.jsxs("div",{className:"grid grid-cols-3 gap-1.5",children:[e.jsx(K,{type:"number",step:"0.01",placeholder:x.dosePlaceholder,value:g.dosis??"",onChange:c=>M(w,{dosis:c.target.value===""?null:Number(c.target.value)}),className:"h-7 text-xs",readOnly:t}),e.jsx(K,{placeholder:x.unitPlaceholder,value:g.unidad??"",onChange:c=>M(w,{unidad:c.target.value||null}),className:"h-7 text-xs",readOnly:t}),e.jsx(K,{placeholder:x.notesPlaceholder,value:g.observaciones??"",onChange:c=>M(w,{observaciones:c.target.value||null}),className:"h-7 text-xs col-span-1",readOnly:t})]})]},`${g.articulo_id}-${w}`))})]})},$t=({protocoloId:a})=>{const{data:l,isLoading:t}=Ss(a),{t:h}=ie(),i=h.procesoSanidad.impact;return a?e.jsxs("div",{className:"rounded-md border border-border bg-muted/20 p-3 space-y-2",children:[e.jsx("p",{className:"text-[11px] uppercase tracking-wider text-muted-foreground font-medium",children:i.title}),t?e.jsxs("div",{className:"flex items-center gap-2 text-xs text-muted-foreground",children:[e.jsx(oe,{className:"h-3.5 w-3.5 animate-spin"}),i.calculating]}):l?l.procesos_afectados===0&&l.eventos_planificados===0&&l.eventos_pen
1dientes_vencidos===0?e.jsx("p",{className:"text-xs text-muted-foreground italic",children:i.noUsage}):e.jsxs("ul",{className:"text-xs space-y-1",children:[e.jsxs("li",{className:"flex items-center gap-2",children:[e.jsx(ss,{className:"h-3 w-3 text-foreground/70"}),e.jsx("strong",{children:l.procesos_afectados})," ",i.processesUsePre]}),e.jsxs("li",{className:"flex items-center gap-2",children:[e.jsx(Vs,{className:"h-3 w-3 text-foreground/70"}),e.jsx("strong",{children:l.eventos_planificados})," ",i.eventsPlanned]}),l.eventos_pendientes_vencidos>0&&e.jsxs("li",{className:"flex items-center gap-2 text-red-700 dark:text-red-400",children:[e.jsx(me,{className:"h-3 w-3"}),e.jsx("strong",{children:l.eventos_pendientes_vencidos})," ",i.overduePending]})]}):e.jsx("p",{className:"text-xs text-muted-foreground italic",children:i.noData}),e.jsx("p",{className:"text-[10px] text-muted-foreground/80 italic",children:i.note})]}):null},It=["Vaca","Toro","Toro capón","Vaquillona","Novillo","Novillito","Ternera","Ternero","Vaquillona Recría","Novillito Recría"],Rt=["nacimiento","pre_servicio","preparto","post_parto","tacto","pre_destete","destete","ingreso_corral","recria","terminacion","engorde","anual"],Lt=["subcutanea","intramuscular","oral","topica","intravenosa"],Mt=["servicio","parto","destete","ingreso_corral","nacimiento","recria","engorde","anual"],Ye={nombre_protocolo:"",descripcion:"",categoria:"Vaca",etapa:"anual",tipo_protocolo:"vacuna",producto_tipo:"",principio_activo:"",via:"__none__",dosis_descripcion:"",dias_previos_evento:0,evento_referencia:"anual",frecuencia_dias:null,obligatorio_senasa:!1,descripcion_capatai:"",orden_display:0},zt=({open:a,onOpenChange:l,protocolo:t,onSave:h})=>{const{toast:i}=Pe(),{t:x}=ie(),d=x.procesoSanidad.form,[s,b]=p.useState(Ye),[R,$]=p.useState([]),[D,L]=p.useState(!1),{articulos:M}=Qe(t==null?void 0:t.id);p.useEffect(()=>{a&&(t?b({nombre_protocolo:t.nombre_protocolo,descripcion:t.descripcion??"",categoria:t.categoria,etapa:t.etapa,tipo_protocolo:t.tipo_protocolo,producto_tipo:t.producto_tipo??"",principio_activo:t.principio_activo??"",via:t.via??"__none__",dosis_descripcion:t.dosis_descripcion??"",dias_previos_evento:t.dias_previos_evento??0,evento_referencia:t.evento_referencia,frecuencia_dias:t.frecuencia_dias,obligatorio_senasa:t.obligatorio_senasa,descripcion_capatai:t.descripcion_capatai??"",orden_display:t.orden_display??0}):(b(Ye),$([])))},[a,t]),p.useEffect(()=>{t&&$(M.map(c=>({articulo_id:c.articulo_id,articulo_nombre:c.articulo_nombre,articulo_sku:c.articulo_sku,articulo_activo:c.articulo_activo,dosis:c.dosis,unidad:c.unidad,observaciones:c.observaciones})))},[t,M]);const g=p.useMemo(()=>t?d.editTitle:d.newTitle,[t,d]),w=async()=>{if(!s.nombre_protocolo.trim()){i({title:d.missingName,variant:"destructive"});return}L(!0);const c={nombre_protocolo:s.nombre_protocolo.trim(),descripcion:s.descripcion.trim()||null,categoria:s.categoria,etapa:s.etapa,tipo_protocolo:s.tipo_protocolo,producto_tipo:s.producto_tipo.trim(),principio_activo:s.principio_activo.trim()||null,via:s.via==="__none__"?null:s.via,dosis_descripcion:s.dosis_descripcion.trim()||null,dias_previos_evento:s.dias_previos_evento,evento_referencia:s.evento_referencia,frecuencia_dias:s.frecuencia_dias,obligatorio_senasa:s.obligatorio_senasa,descripcion_capatai:s.descripcion_capatai.trim()||null,orden_display:s.orden_display},N=await h(c,R);L(!1),N.ok?(i({title:t?d.protocolUpdated:d.protocolCreated}),l(!1)):i({title:d.saveError,description:N.error,variant:"destructive"})};return e.jsx(Es,{open:a,onOpenChange:l,children:e.jsxs(Ts,{className:"w-full sm:max-w-lg overflow-y-auto",side:"right",children:[e.jsxs(Ds,{children:[e.jsx(As,{children:g}),t&&e.jsxs(Fs,{className:"text-xs",children:[d.version," ",t.version," · ",t.activo?d.active:d.deactivated]})]}),e.jsxs("div",{className:"mt-4 space-y-4",children:[e.jsxs("section",{className:"space-y-2",children:[e.jsx("p",{className:"text-[11px] uppercase tracking-wider text-muted-foreground font-medium",children:d.sectionGeneral}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsxs(V,{className:"text-xs",children:[d.name," ",e.jsx("span",{className:"text-red-600",children:"*"})]}),e.jsx(K,{value:s.nombre_protocolo,onChange:c=>b(N=>({...N,nombre_protocolo:c.target.value})),placeholder:d.namePlaceholder})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(V,{className:"text-xs",children:d.description}),e.jsx($s,{value:s.descripcion,onChange:c=>b(N=>({...N,descripcion:c.target.value})),placeholder:d.descriptionPlaceholder,rows:2})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-2",children:[e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(V,{className:"text-xs",children:d.animalCategory}),e.jsxs(Y,{value:s.categoria,onValueChange:c=>b(N=>({...N,categoria:c})),children:[e.jsx(J,{className:"h-9 text-sm",children:e.jsx(X,{})}),e.jsx(Z,{children:It.map(c=>e.jsx(k,{value:c,children:c},c))})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(V,{className:"text-xs",children:d.stage}),e.jsxs(Y,{value:s.etapa,onValueChange:c=>b(N=>({...N,etapa:c})),children:[e.jsx(J,{className:"h-9 text-sm",children:e.jsx(X,{})}),e.jsx(Z,{children:Rt.map(c=>e.jsx(k,{value:c,children:x.procesoSanidad.etapas[c]},c))})]})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(V,{className:"text-xs",children:d.type}),e.jsxs(Y,{value:s.tipo_protocolo,onValueChange:c=>b(N=>({...N,tipo_protocolo:c})),children:[e.jsx(J,{className:"h-9 text-sm",children:e.jsx(X,{})}),e.jsx(Z,{children:ze.map(c=>e.jsx(k,{value:c,children:x.procesoSanidad.tipos[c]},c))})]})]})]}),e.jsxs("section",{className:"space-y-2",children:[e.jsx("p",{className:"text-[11px] uppercase tracking-wider text-muted-foreground font-medium",children:d.sectionScheduling}),e.jsxs("div",{className:"grid grid-cols-2 gap-2",children:[e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(V,{className:"text-xs",children:d.referenceEvent}),e.jsxs(Y,{value:s.evento_referencia,onValueChange:c=>b(N=>({...N,evento_referencia:c})),children:[e.jsx(J,{className:"h-9 text-sm",children:e.jsx(X,{})}),e.jsx(Z,{children:Mt.map(c=>e.jsx(k,{value:c,children:x.procesoSanidad.eventosRef[c]},c))})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(V,{className:"text-xs",children:d.daysFromEvent}),e.jsx(K,{type:"number",value:s.dias_previos_evento,onChange:c=>b(N=>({...N,dias_previos_evento:Number(c.target.value)||0}))})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(V,{className:"text-xs",children:d.frequencyLabel}),e.jsx(K,{type:"number",value:s.frecuencia_dias??"",onChange:c=>b(N=>({...N,frecuencia_dias:c.target.value===""?null:Number(c.target.value)})),placeholder:d.frequencyPlaceholder})]})]}),e.jsxs("section",{className:"space-y-2",children:[e.jsx("p",{className:"text-[11px] uppercase tracking-wider text-muted-foreground font-medium",children:d.sectionProduct}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(V,{className:"text-xs",children:d.productType}),e.jsx(K,{value:s.producto_tipo,onChange:c=>b(N=>({...N,producto_tipo:c.target.value})),placeholder:d.productTypePlaceholder})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-2",children:[e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(V,{className:"text-xs",children:d.activeIngredient}),e.jsx(K,{value:s.principio_activo,onChange:c=>b(N=>({...N,principio_activo:c.target.value}))})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(V,{className:"text-xs",children:d.route}),e.jsxs(Y,{value:s.via,onValueChange:c=>b(N=>({...N,via:c})),children:[e.jsx(J,{className:"h-9 text-sm",children:e.jsx(X,{})}),e.jsxs(Z,{children:[e.jsx(k,{value:"__none__",children:"—"}),Lt.map(c=>e.jsx(k,{value:c,children:x.procesoSanidad.vias[c]},c))]})]})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(V,{className:"text-xs",children:d.doseLabel}),e.jsx(K,{value:s.dosis_descripcion,onChange:c=>b(N=>({...N,dosis_descripcion:c.target.value})),placeholder:d.dosePlaceholder})]})]}),e.jsxs("section",{className:"space-y-2",children:[e.jsx("p",{className:"text-[11px] uppercase tracking-wider text-muted-foreground font-medium",children:d.sectionMarkers}),e.jsxs("div",{className:"flex items-center justify-between rounded-md border border-border bg-card px-3 py-2",children:[e.jsxs("div",{children:[e.jsx(V,{className:"text-sm",children:d.senasaMandatory}),e.jsx("p",{className:"text-[11px] text-muted-foreground",children:d.senasaMandatoryHint})]}),e.jsx(Is,{checked:s.obligatorio_senasa,onCheckedChange:c=>b(N=>({...N,obligatorio_senasa:c}))})]})]}),e.jsxs("section",{className:"space-y-2",children:[e.jsx("p",{className:"text-[11px] uppercase tracking-wider text-muted-foreground font-medium",children:d.sectionArticles}),e.jsx(Ft,{items:R,onChange:$})]}),t&&e.jsx($t,{protocoloId:t.id})]}),e.jsx("div",{className:"sticky bottom-0 left-0 right-0 mt-4 -mx-6 px-6 py-3 bg-background border-t border-border",children:e.jsxs("div",{className:"flex justify-end gap-2",children:[e.jsx(C,{variant:"ghost",size:"sm",onClick:()=>l(!1),disabled:D,children:d.cancel}),e.jsx(C,{size:"sm",onClick:w,disabled:D,children:D?e.jsxs(e.Fragment,{children:[e.jsx(oe,{className:"h-3.5 w-3.5 mr-1 animate-spin"})," ",d.saving]}):e.jsxs(e.Fragment,{children:[e.jsx(Os,{className:"h-3.5 w-3.5 mr-1"})," ",t?d.saveChanges:d.createProtocol]})})]})})]})})},Vt=({open:a,onOpenChange:l,protocolosExistentes:t,establecimientoId:h,onImportFinalizada:i})=>{const{toast:x}=Pe(),{t:d}=ie(),s=d.procesoSanidad.import,{user:b}=Re(),{parsing:R,error:$,data:D,parseFile:L,reset:M}=Zs(),[g,w]=p.useState(1),[c,N]=p.useState([]),[ce,A]=p.useState(new Map),[B,H]=p.useState(!1),[O,ne]=p.useState(!1);p.useEffect(()=>{a||(M(),w(1),N([]),A(new Map),ne(!1))}
1,[a,M]),p.useEffect(()=>{if(!D)return;let f=!1;return(async()=>{H(!0);const{data:y}=await se.from("articulos").select("id, sku").eq("activo",!0);if(f)return;const _=new Map;for(const o of y??[])o.sku&&_.set(String(o.sku).trim().toUpperCase(),o.id);A(_);const q=D.rows.map((o,r)=>St(o,r)),n=kt(q,{protocolosExistentes:t,articulosPorSku:_});N(n),w(2),H(!1)})(),()=>{f=!0}},[D,t]);const E=p.useMemo(()=>Pt(c),[c]),U=async f=>{await L(f)},Q=async()=>{if(O)return;const f=c.filter(y=>y.accion!=="error");if(f.length===0){x({title:s.noValidRowsTitle,description:s.noValidRowsDesc,variant:"destructive"});return}ne(!0);try{let y=0,_=0,q=0,n=0;for(const o of f){const r=Tt(o);let m=null;if(o.accion==="crear"){const{data:j,error:v}=await se.from("protocolos_sanitarios").insert({...r,establecimiento_id:h,created_by_user_id:(b==null?void 0:b.id)??null,version:1}).select("id").single();if(v){n++,console.error("[import-protocolos] INSERT failed",o.rowIndex,v.message);continue}m=j.id,y++}else if(o.accion==="actualizar"&&o.protocoloExistenteId){const{data:j}=await se.from("protocolos_sanitarios").select("version").eq("id",o.protocoloExistenteId).single(),{error:v}=await se.from("protocolos_sanitarios").update({...r,version:((j==null?void 0:j.version)??1)+1}).eq("id",o.protocoloExistenteId);if(v){n++,console.error("[import-protocolos] UPDATE failed",o.rowIndex,v.message);continue}m=o.protocoloExistenteId,_++}if(m&&o.articuloMatchId){await se.from("protocolo_articulos").delete().eq("protocolo_id",m).eq("articulo_id",o.articuloMatchId);const{error:j}=await se.from("protocolo_articulos").insert({protocolo_id:m,articulo_id:o.articuloMatchId,dosis:o.dosis,unidad:o.unidad||null,observaciones:o.observaciones||null,orden:0});j||q++}}x({title:s.importComplete,description:`${y} ${y===1?s.createdSingular:s.createdPlural}, ${_} ${_===1?s.updatedSingular:s.updatedPlural}`+(q>0?`, ${q} ${q===1?s.linkedSingular:s.linkedPlural}`:"")+(n>0?`${s.rowsWithDbErrorPre} ${n} ${n===1?s.rowSingularErr:s.rowPluralErr} ${s.withDbError}`:""),variant:n>0?"destructive":"default"}),i(),l(!1)}catch(y){console.error("[import-protocolos] error inesperado",y),x({title:s.importError,description:y instanceof Error?y.message:s.unknownError,variant:"destructive"})}finally{ne(!1)}},I=c,z=I.slice(0,200);return e.jsx(Us,{open:a,onOpenChange:l,children:e.jsxs(Bs,{className:"max-w-5xl max-h-[90vh] overflow-y-auto",children:[e.jsxs(Hs,{children:[e.jsxs(qs,{className:"flex items-center gap-2",children:[e.jsx(Be,{className:"h-5 w-5 text-primary"}),s.title]}),e.jsx(Gs,{className:"text-xs",children:s.desc})]}),e.jsx("div",{className:"flex items-center justify-center gap-2 py-2 text-xs",children:[1,2].map(f=>e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("div",{className:ae("h-6 w-6 rounded-full flex items-center justify-center text-[10px] font-bold",g===f?"bg-primary text-primary-foreground":g>f?"bg-emerald-500 text-white":"bg-muted text-muted-foreground"),children:g>f?e.jsx($e,{className:"h-3.5 w-3.5"}):f}),e.jsx("span",{className:g===f?"font-semibold":"text-muted-foreground",children:f===1?s.stepUpload:s.stepReview}),f<2&&e.jsx(Ve,{className:"h-3 w-3 text-muted-foreground"})]},f))}),e.jsx(Ks,{}),g===1&&e.jsxs("div",{className:"space-y-4 py-4",children:[e.jsxs("label",{htmlFor:"protocolos-excel-input",className:"block rounded-lg border-2 border-dashed border-border hover:border-primary/50 hover:bg-primary/5 transition-colors p-10 text-center cursor-pointer",children:[R||B?e.jsxs(e.Fragment,{children:[e.jsx(oe,{className:"h-10 w-10 mx-auto text-muted-foreground animate-spin mb-3"}),e.jsx("p",{className:"text-sm font-medium",children:s.processing})]}):e.jsxs(e.Fragment,{children:[e.jsx(ts,{className:"h-10 w-10 mx-auto text-muted-foreground mb-3"}),e.jsx("p",{className:"text-sm font-medium",children:s.clickToSelect}),e.jsx("p",{className:"text-xs text-muted-foreground mt-1",children:s.acceptedFormats})]}),e.jsx("input",{id:"protocolos-excel-input",type:"file",accept:".xlsx,.xls,.csv,.tsv",onChange:f=>{var _;const y=(_=f.target.files)==null?void 0:_[0];y&&U(y),f.target.value=""},className:"hidden",disabled:R||B})]}),$&&e.jsxs("div",{className:"rounded-md border border-destructive/50 bg-destructive/10 p-3 flex items-start gap-2",children:[e.jsx(me,{className:"h-4 w-4 text-destructive shrink-0 mt-0.5"}),e.jsx("div",{className:"text-xs text-destructive",children:$})]}),e.jsxs("div",{className:"rounded-md bg-muted/30 p-3 text-[11px] text-muted-foreground space-y-1",children:[e.jsx("p",{className:"font-semibold text-foreground",children:s.howItWorks}),e.jsxs("p",{children:[s.howItWorks1Pre," ",e.jsx("strong",{children:s.howItWorks1Upsert})," ",s.howItWorks1Mid,e.jsx("span",{className:"font-mono",children:" categoria_animal + etapa_productiva + nombre_protocolo"}),s.howItWorks1Post]}),e.jsxs("p",{children:[s.howItWorks2Pre," ",e.jsx("span",{className:"font-mono",children:"articulo_sku"})," ",s.howItWorks2Post]})]})]}),g===2&&D&&e.jsxs("div",{className:"space-y-4 py-2",children:[e.jsxs("div",{className:"grid grid-cols-2 sm:grid-cols-4 gap-3",children:[e.jsxs("div",{className:"rounded-md border border-emerald-500/30 bg-emerald-500/5 p-3 text-center",children:[e.jsx("p",{className:"text-[10px] text-muted-foreground",children:s.summaryNew}),e.jsx("p",{className:"text-xl font-bold text-emerald-600",children:E.nuevos})]}),e.jsxs("div",{className:"rounded-md border border-blue-500/30 bg-blue-500/5 p-3 text-center",children:[e.jsx("p",{className:"text-[10px] text-muted-foreground",children:s.summaryUpdate}),e.jsx("p",{className:"text-xl font-bold text-blue-600",children:E.actualizados})]}),e.jsxs("div",{className:"rounded-md border border-amber-500/30 bg-amber-500/5 p-3 text-center",children:[e.jsx("p",{className:"text-[10px] text-muted-foreground",children:s.summaryWarnings}),e.jsx("p",{className:"text-xl font-bold text-amber-600",children:E.conWarnings})]}),e.jsxs("div",{className:"rounded-md border border-destructive/30 bg-destructive/5 p-3 text-center",children:[e.jsx("p",{className:"text-[10px] text-muted-foreground",children:s.summaryErrors}),e.jsx("p",{className:"text-xl font-bold text-destructive",children:E.errores})]})]}),e.jsxs("div",{className:"rounded-md bg-muted/30 p-3 text-xs flex items-center gap-2 flex-wrap",children:[e.jsx(Be,{className:"h-4 w-4 text-primary"}),e.jsxs("span",{children:[s.sheet," ",e.jsx("strong",{children:D.sheetName})," · ",E.total," ",E.total===1?s.rowSingular:s.rowPlural]}),E.errores>0&&e.jsxs(F,{variant:"outline",className:"text-[10px] bg-destructive/10 text-destructive border-destructive/40",children:[E.errores," ",s.wontImport]})]}),e.jsx("div",{className:"rounded-md border border-border overflow-hidden",children:e.jsx("div",{className:"overflow-x-auto max-h-[40vh] overflow-y-auto",children:e.jsxs(Ys,{children:[e.jsx(Js,{className:"sticky top-0 bg-background z-10",children:e.jsxs(Ue,{children:[e.jsx(ue,{className:"text-[10px] w-12",children:s.thRow}),e.jsx(ue,{className:"text-[10px]",children:s.thProtocol}),e.jsx(ue,{className:"text-[10px]",children:s.thCategoryStage}),e.jsx(ue,{className:"text-[10px]",children:s.thType}),e.jsx(ue,{className:"text-[10px] w-24",children:s.thAction}),e.jsx(ue,{className:"text-[10px]",children:s.thNotices})]})}),e.jsx(Xs,{children:z.map(f=>e.jsxs(Ue,{className:ae(f.accion==="error"&&"bg-destructive/5",f.accion==="actualizar"&&"bg-blue-500/5",f.warnings.length>0&&f.accion!=="error"&&"bg-amber-500/5"),children:[e.jsx(he,{className:"text-[10px] font-mono",children:f.rowIndex}),e.jsxs(he,{className:"text-xs max-w-[240px]",children:[e.jsx("div",{className:"truncate font-medium",children:f.nombre_protocolo||e.jsx("span",{className:"text-destructive",children:s.noName})}),f.articulo_sku&&e.jsxs("div",{className:"text-[10px] text-muted-foreground font-mono truncate",children:[s.skuLabel," ",f.articulo_sku,f.articuloMatchId?e.jsx("span",{className:"text-emerald-600 ml-1",children:s.skuFound}):e.jsx("span",{className:"text-amber-600 ml-1",children:s.skuNotFound})]})]}),e.jsxs(he,{className:"text-[10px] text-muted-foreground max-w-[160px]",children:[e.jsx("div",{className:"truncate",children:f.categoria_animal||"—"}),e.jsx("div",{className:"truncate font-mono",children:f.etapa_productiva||"—"})]}),e.jsx(he,{className:"text-[10px]",children:f.tipo_protocolo||"—"}),e.jsxs(he,{children:[f.accion==="crear"&&e.jsx(F,{variant:"outline",className:"text-[10px] bg-emerald-500/10 text-emerald-700 border-emerald-500/40",children:s.actionCreate}),f.accion==="actualizar"&&e.jsx(F,{variant:"outline",className:"text-[10px] bg-blue-500/10 text-blue-700 border-blue-500/40",children:s.actionUpdate}),f.accion==="error"&&e.jsx(F,{variant:"outline",className:"text-[10px] bg-destructive/10 text-destructive border-destructive/40",children:s.actionError})]}),e.jsxs(he,{className:"text-[10px] max-w-[260px]",children:[f.errores.length>0&&e.jsx("ul",{className:"text-destructive space-y-0.5",children:f.errores.map((y,_)=>e.jsxs("li",{className:"truncate",title:y,children:["• ",y]},`e${_}`))}),f.warnings.length>0&&e.jsx("ul",{className:"text-amber-600 space-y-0.5 mt-0.5",children:f.warnings.map((y,_)=>e.jsxs("li",{className:"truncate",title:y,children:["• ",y]},`w${_}`))}),f.errores.length===0&&f.warnings.length===0&&e.jsx("span",{className:"text-muted-foreground",children:"—"})]})]},f.rowIndex))})]})})}),I.length>200&&e.jsxs("p",{className:"text-[10px] text-muted-foreground",children:[s.showingFirstPre," ",I.length," ",s.showingFirstPost]}),E.nuevos+E.actualizados===0&&e.jsxs("div",{className:"rounded-md border border-destructive/30 bg-destructive/5 p-3 flex items-start gap-2",children:[e.jsx(me,{className:"h-4 w-4 text-destructive shrink-0 mt-0.5"}),e.jsx("div",{className:"text-xs text-destructive",children:s.noValidRows})]})]}),e.jsxs(Ws,{className:"flex justify-between sm:justify-between gap-2",children:[e.jsx(C,{type:"button",variant:"outline",onClick:()=>{g===1?l(!1):w(1)},disabled:O,children:g===1?e.jsxs(e.Fragment,{children:[e.jsx(Le,{className:"h-4 w-4 mr-1"})," ",s.cancel]}):e.jsxs(e.Fragment,{children:[e.jsx(Qs,{className:"h-4 w-4 mr-1"})," ",s.backToUpload]})}),g===2&&e.jsx(C,{type:"button",onClick:Q,disabled:O||E.nuevos+E.actualizados===0,children:O?e.jsxs(e.Fragment,{children:[e.jsx(oe,{className:"h-4 w-4 mr-1 animate-spin"})," ",s.importing]}):e.jsxs(e.Fragment,{children:[e.jsx($e,{className:"h-4 w-4 mr-1"}),s.confirmPrefix," ",E.nuevos," ",E.nuevos===1?s.confirmNewSingular:s.confirmNewPlural," · ",E.actualizados," ",E.actualizados===1?s.confirmUpdatedSingular:s.confirmUpdatedPlural]})})]})]})})},Ot={vacuna:"bg-blue-500/10 text-blue-700 dark:text-blue-400 border-blue-500/40",antiparasitario:"bg-purple-500/10 text-purple-700 dark:text-purple-400 border-purple-500/40",suplementacion:"bg-emerald-500/10 text-emerald-700 dark:text-emerald-400 border-emerald-500/40",mineralizacion:"bg-teal-500/10 text-teal-700 dark:text-teal-400 border-teal-500/40",observacion:"bg-muted text-muted-foreground border-border",manejo:"bg-amber-500/10 text-amber-700 dark:text-amber-400 border-amber-500/40",senasa:"bg-red-500/10 text-red-700 dark:text-red-400 border-red-500/40",otro:"bg-muted text-muted-foreground border-border"},Ut=()=>{const{toast:a}=Pe(),{t:l}=ie(),t=l.procesoSanidad.protocols,[h,i]=p.useState(""),[x,d]=p.useState(""),[s,b]=p.useState(""),[R,$]=p.useState(""),[D,L]=p.useState("activos"),{loading:M,filtered:g,protocolos:w,establecimientoId:c,seedError:N,seedRunning:ce,refetch:A,crear:B,actualizar:H,softDelete:O,restaurar:ne,hardDelete:E,duplicar:U}=ks({search:h,categoria:x||void 0,etapa:s||void 0,tipo:R||void 0,estadoFilter:D}),[Q,I]=p.useState(!1),[z,f]=p.useState(null),[y,_]=p.useState(null),[q,n]=p.useState(!1),[o,r]=p.useState(!1),[m,j]=p.useState(new Set),v=p.useMemo(()=>{const u=new Map;for(const P of g){u.has(P.categoria)||u.set(P.categoria,new Map);const T=u.get(P.categoria);T.has(P.etapa)||T.set(P.etapa,[]),T.get(P.etapa).push(P)}return[...u.entries()].sort(([P],[T])=>P.localeCompare(T)).map(([P,T])=>({categoria:P,etapas:[...T.entries()].sort(([pe],[ee])=>pe.localeCompare(ee)).map(([pe,ee])=>({etapa:pe,items:ee}))}))},[g]),S=u=>{j(P=>{const T=new Set(P);return T.has(u)?T.delete(u):T.add(u),T})}
1,G=[x,s,R,h].filter(Boolean).length+(D!=="activos"?1:0),xe=()=>{i(""),d(""),b(""),$(""),L("activos")},je=()=>{f(null),I(!0)},Ee=async()=>{if(!o){r(!0);try{await Et(),a({title:t.templateDownloaded})}catch(u){a({title:t.templateError,description:u instanceof Error?u.message:t.unknownError,variant:"destructive"})}finally{r(!1)}}},rs=()=>{if(!c){a({title:t.waitingCatalogTitle,description:t.waitingCatalogDesc,variant:"destructive"});return}n(!0)},os=u=>{f(u),I(!0)},is=async u=>{const P=await U(u.id);P.ok?a({title:`${t.duplicatedPre} ${u.nombre_protocolo} ${t.duplicatedSuffix}`}):a({title:t.duplicateError,description:P.error,variant:"destructive"})},cs=async u=>{const P=u.activo?await O(u.id):await ne(u.id);P.ok?a({title:u.activo?t.protocolDeactivated:t.protocolReactivated}):a({title:t.error,description:P.error,variant:"destructive"})},ns=async()=>{if(!y)return;const u=await E(y.id);u.ok?a({title:t.protocolDeleted}):a({title:t.deleteFailed,description:u.error,variant:"destructive"}),_(null)},ls=async(u,P)=>{if(z){const T=await H(z.id,u);return T.ok?(await Je(z.id,P),{ok:!0}):T}else{const T=await B(u);return!T.ok||!T.protocolo?{ok:!1,error:T.error}:(await Je(T.protocolo.id,P),{ok:!0})}};return e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex flex-col sm:flex-row sm:items-start sm:justify-between gap-3",children:[e.jsx("div",{children:e.jsxs("p",{className:"text-muted-foreground text-sm",children:[t.intro1," ",e.jsx("strong",{children:t.introGenerate}),t.intro2]})}),e.jsxs("div",{className:"flex flex-wrap items-center gap-2 sm:shrink-0",children:[e.jsxs(C,{type:"button",variant:"outline",size:"sm",onClick:Ee,disabled:o,children:[o?e.jsx(oe,{className:"h-4 w-4 mr-1 animate-spin"}):e.jsx(et,{className:"h-4 w-4 mr-1"}),t.downloadTemplate]}),e.jsxs(C,{type:"button",variant:"outline",size:"sm",onClick:rs,children:[e.jsx(ts,{className:"h-4 w-4 mr-1"}),t.importExcel]}),e.jsxs(C,{onClick:je,size:"sm",children:[e.jsx(fe,{className:"h-4 w-4 mr-1"})," ",t.newProtocol]})]})]}),e.jsx(re,{className:"shadow-card",children:e.jsxs(W,{className:"py-3 space-y-2",children:[e.jsxs("div",{className:"flex flex-col sm:flex-row gap-2 flex-wrap",children:[e.jsxs("div",{className:"relative flex-1 min-w-[200px]",children:[e.jsx(es,{className:"absolute left-2.5 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(K,{placeholder:t.searchPlaceholder,value:h,onChange:u=>i(u.target.value),className:"pl-9 h-9 text-sm"})]}),e.jsxs(Y,{value:x||"__all__",onValueChange:u=>d(u==="__all__"?"":u),children:[e.jsx(J,{className:"h-9 w-full sm:w-40 text-sm",children:e.jsx(X,{placeholder:t.filterCategory})}),e.jsxs(Z,{children:[e.jsx(k,{value:"__all__",children:t.allCategories}),["Vaca","Toro","Toro capón","Vaquillona","Novillo","Novillito","Ternera","Ternero","Vaquillona Recría","Novillito Recría"].map(u=>e.jsx(k,{value:u,children:u},u))]})]}),e.jsxs(Y,{value:s||"__all__",onValueChange:u=>b(u==="__all__"?"":u),children:[e.jsx(J,{className:"h-9 w-full sm:w-36 text-sm",children:e.jsx(X,{placeholder:t.filterStage})}),e.jsxs(Z,{children:[e.jsx(k,{value:"__all__",children:t.allStages}),["nacimiento","pre_servicio","preparto","post_parto","tacto","pre_destete","destete","ingreso_corral","recria","terminacion","engorde","anual"].map(u=>e.jsx(k,{value:u,children:l.procesoSanidad.etapas[u]},u))]})]}),e.jsxs(Y,{value:R||"__all__",onValueChange:u=>$(u==="__all__"?"":u),children:[e.jsx(J,{className:"h-9 w-full sm:w-36 text-sm",children:e.jsx(X,{placeholder:t.filterType})}),e.jsxs(Z,{children:[e.jsx(k,{value:"__all__",children:t.allTypes}),ze.map(u=>e.jsx(k,{value:u,children:l.procesoSanidad.tipos[u]},u))]})]}),e.jsxs(Y,{value:D,onValueChange:u=>L(u),children:[e.jsx(J,{className:"h-9 w-full sm:w-32 text-sm",children:e.jsx(X,{})}),e.jsxs(Z,{children:[e.jsx(k,{value:"activos",children:t.stateActive}),e.jsx(k,{value:"inactivos",children:t.stateInactive}),e.jsx(k,{value:"todos",children:t.stateAll})]})]})]}),G>0&&e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(st,{className:"h-3.5 w-3.5 text-muted-foreground"}),e.jsxs("span",{className:"text-xs text-muted-foreground",children:[g.length," ",g.length===1?t.protocolSingular:t.protocolPlural]}),e.jsxs(C,{variant:"ghost",size:"sm",onClick:xe,className:"text-xs h-6 px-2 ml-auto",children:[e.jsx(Le,{className:"h-3 w-3 mr-1"}),t.clearFilters]})]})]})}),M?e.jsx("div",{className:"flex items-center justify-center py-12",children:e.jsx(oe,{className:"h-6 w-6 animate-spin text-muted-foreground"})}):v.length===0?e.jsx(re,{className:"shadow-card",children:e.jsxs(W,{className:"py-10 text-center space-y-2",children:[e.jsx(Ie,{className:"h-10 w-10 text-muted-foreground
1/40 mx-auto"}),G>0?e.jsx("p",{className:"text-sm text-muted-foreground",children:t.emptyFiltered}):c?N?e.jsxs("div",{className:"space-y-2 max-w-lg mx-auto",children:[e.jsx("p",{className:"text-sm font-medium text-destructive",children:t.seedErrorTitle}),e.jsx("p",{className:"text-xs text-destructive/80 break-words text-left bg-destructive/5 border border-destructive/30 rounded-md p-2",children:N}),e.jsxs("p",{className:"text-[11px] text-muted-foreground italic",children:[t.seedErrorHintPre," ",e.jsx("code",{children:"[protocolos]"}),t.seedErrorHintPost]})]}):ce?e.jsx("p",{className:"text-sm text-muted-foreground",children:t.seedRunning}):e.jsxs(e.Fragment,{children:[e.jsx("p",{className:"text-sm text-muted-foreground",children:t.emptyCatalog}),e.jsxs("p",{className:"text-xs text-muted-foreground/80",children:[t.emptyCatalogHintPre," ",e.jsx("strong",{children:t.emptyCatalogHintNew})," ",t.emptyCatalogHintMid," ",e.jsx("strong",{children:t.emptyCatalogHintImport})," ",t.emptyCatalogHintEnd]})]}):e.jsxs(e.Fragment,{children:[e.jsx("p",{className:"text-sm text-muted-foreground",children:t.waitingEstablishment}),e.jsx("p",{className:"text-xs text-muted-foreground/80",children:t.waitingEstablishmentHint})]})]})}):e.jsx("div",{className:"space-y-3",children:v.map(u=>{const P=`cat:${u.categoria}`,T=m.has(P),pe=u.etapas.reduce((ee,de)=>ee+de.items.length,0);return e.jsx(re,{className:"shadow-card",children:e.jsxs(W,{className:"p-0",children:[e.jsxs("button",{type:"button",onClick:()=>S(P),className:"w-full flex items-center gap-2 px-4 py-3 hover:bg-muted/30 transition-colors text-left",children:[T?e.jsx(Ve,{className:"h-4 w-4 text-muted-foreground"}):e.jsx(Me,{className:"h-4 w-4 text-muted-foreground"}),e.jsx("h2",{className:"font-semibold text-foreground",children:u.categoria}),e.jsxs("span",{className:"text-xs text-muted-foreground",children:["· ",pe," ",pe===1?t.protocolSingular:t.protocolPlural]})]}),!T&&e.jsx("div",{className:"border-t border-border",children:u.etapas.map(ee=>e.jsxs(p.Fragment,{children:[e.jsxs("div",{className:"px-4 py-2 bg-muted/20 border-b border-border/50",children:[e.jsx("span",{className:"text-[11px] uppercase tracking-wider text-muted-foreground font-medium",children:l.procesoSanidad.etapas[ee.etapa]??ee.etapa}),e.jsxs("span",{className:"text-[11px] text-muted-foreground/60 ml-2",children:["(",ee.items.length,")"]})]}),e.jsx("ul",{className:"divide-y divide-border",children:ee.items.map(de=>e.jsx(Bt,{protocolo:de,onEdit:()=>os(de),onDuplicar:()=>is(de),onToggleActivo:()=>cs(de),onDelete:()=>_(de)},de.id))})]},`${P}/etapa:${ee.etapa}`))})]})},P)}
1)}),e.jsx(zt,{open:Q,onOpenChange:I,protocolo:z,onSave:ls}),c&&e.jsx(Vt,{open:q,onOpenChange:n,establecimientoId:c,protocolosExistentes:w,onImportFinalizada:()=>A()}),e.jsx(js,{open:!!y,onOpenChange:u=>!u&&_(null),children:e.jsxs(vs,{children:[e.jsxs(bs,{children:[e.jsx(Ns,{children:t.deleteTitle}),e.jsx(_s,{children:y&&e.jsxs(e.Fragment,{children:[t.deleteDescPre," ",e.jsx("strong",{children:y.nombre_protocolo})," ",t.deleteDescPost]})})]}),e.jsxs(ws,{children:[e.jsx(Cs,{children:t.cancel}),e.jsx(ys,{onClick:ns,children:t.delete})]})]})})]})};async function Je(a,l){await se.from("protocolo_articulos").delete().eq("protocolo_id",a),l.length!==0&&await se.from("protocolo_articulos").insert(l.map((t,h)=>({protocolo_id:a,articulo_id:t.articulo_id,dosis:t.dosis,unidad:t.unidad,observaciones:t.observaciones,orden:h})))}const Bt=({protocolo:a,onEdit:l,onDuplicar:t,onToggleActivo:h,onDelete:i})=>{const{articulos:x}=Qe(a.id),{t:d}=ie(),s=d.procesoSanidad.protocols;return e.jsxs("li",{className:ae("flex items-center gap-3 px-4 py-2.5 hover:bg-muted/20 transition-colors",!a.activo&&"opacity-60"),children:[e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[e.jsx("p",{className:"text-sm font-medium text-foreground truncate",children:a.nombre_protocolo}),e.jsx(F,{variant:"outline",className:ae("text-[10px]",Ot[a.tipo_protocolo]),children:d.procesoSanidad.tipos[a.tipo_protocolo]??s.typeFallback}),a.obligatorio_senasa&&e.jsx(F,{variant:"outline",className:"text-[10px] bg-red-500/10 text-red-700 dark:text-red-400 border-red-500/40",children:"SENASA"}),!a.activo&&e.jsx(F,{variant:"outline",className:"text-[10px]",children:s.inactiveBadge})]}),e.jsxs("div",{className:"flex items-center gap-3 mt-0.5 text-[11px] text-muted-foreground flex-wrap",children:[e.jsx("span",{children:a.frecuencia_dias?`${s.everyDaysPre} ${a.frecuencia_dias} ${s.everyDaysPost}`:s.single}),e.jsxs("span",{children:["· ",s.eventLabel," ",d.procesoSanidad.eventosRef[a.evento_referencia]??a.evento_referencia]}),a.dias_previos_evento!==0&&e.jsxs("span",{children:["· ",a.dias_previos_evento>0?"+":"",a.dias_previos_evento,"d"]}),x.length>0&&e.jsxs("span",{className:"flex items-center gap-1",children:["· ",e.jsx(Fe,{className:"h-3 w-3"})," ",x.length," ",x.length===1?s.itemSingular:s.itemPlural]})]})]}),e.jsx(xs,{children:e.jsxs("div",{className:"flex gap-0.5 shrink-0",children:[e.jsxs(Ne,{children:[e.jsx(_e,{asChild:!0,children:e.jsx(C,{variant:"ghost",size:"icon",className:"h-7 w-7",onClick:l,children:e.jsx(tt,{className:"h-3.5 w-3.5"})})}),e.jsx(we,{children:s.edit})]}),e.jsxs(Ne,{children:[e.jsx(_e,{asChild:!0,children:e.jsx(C,{variant:"ghost",size:"icon",className:"h-7 w-7",onClick:t,children:e.jsx(at,{className:"h-3.5 w-3.5"})})}),e.jsx(we,{children:s.duplicate})]}),e.jsxs(Ne,{children:[e.jsx(_e,{asChild:!0,children:e.jsx(C,{variant:"ghost",size:"icon",className:"h-7 w-7 hover:text-amber-500",onClick:h,children:e.jsx(rt,{className:"h-3.5 w-3.5"})})}),e.jsx(we,{children:a.activo?s.deactivate:s.reactivate})]}),e.jsxs(Ne,{children:[e.jsx(_e,{asChild:!0,children:e.jsx(C,{variant:"ghost",size:"icon",className:"h-7 w-7 hover:text-destructive",onClick:i,children:e.jsx(as,{className:"h-3.5 w-3.5"})})}),e.jsx(we,{children:s.delete})]})]})})]})},Se={rojo:0,amarillo:1,verde:2},Ht={forrajero:"🌱",sanitario:"💉",reproductivo:"🐄",rentabilidad:"💰"},ge={criticos:!1,atencion:!0,normal:!0},Xe="centro_op_grupos_collapsed_v1",qt={criticos:{labelKey:"groupCriticos",dot:"bg-red-500",text:"text-red-700 dark:text-red-400",bg:"bg-red-500/10",border:"border-l-red-500",badgePill:"bg-red-700 text-white"},atencion:{labelKey:"groupAtencion",dot:"bg-amber-500",text:"text-amber-700 dark:text-amber-400",bg:"bg-amber-500/10",border:"border-l-amber-500",badgePill:"bg-amber-700 text-white"},normal:{labelKey:"groupNormal",dot:"bg-emerald-500",text:"text-emerald-700 dark:text-emerald-400",bg:"bg-emerald-500/10",border:"border-l-emerald-500",badgePill:"bg-emerald-700 text-white"}};function Ze(a){if(!a)return 0;const l=/hace\s+(\d+)\s*d[ií]as?/i.exec(a);return l?parseInt(l[1],10):0}const Tr=()=>{const{procesos:a,loading:l,refresh:t}=it(),{user:h,activeEstablecimientoId:i}=Re(),{toast:x}=Pe(),{t:d}=ie(),s=d.procesoProductivo.centroOperativo,[b,R]=p.useState(!1),[$,D]=p.useState(!1),[L,M]=p.useState(!1),[g,w]=ps(),c=g.get("vista")??"",N=["sanidad","cc","engorde","protocolos"],ce=N.includes(c)?c:null,[A,B]=p.useState(ce);p.useEffect(()=>{if(c&&!N.includes(c)){const n=new URLSearchParams(g);n.delete("vista"),w(n,{replace:!0})}},[]);const H=n=>{const o=new URLSearchParams(g);A===n?(o.delete("vista"),B(null)):(o.set("vista",n),B(n)),w(o,{replace:!0})},O=async()=>
1{if(!(h!=null&&h.id)||!i){x({title:s.missingActiveFarm,variant:"destructive"});return}D(!0);const n=await ct(i,h.id);if(D(!1),n.error){x({title:s.extDemoFailed,description:n.error,variant:"destructive"});return}if(n.ya_existian){x({title:s.extDemoExists,description:s.extDemoExistsDesc}),t();return}x({title:s.extDemoLoaded,description:`${n.procesos_creados} · ${n.rodeos_creados} · ${n.lotes_creados} · ${n.eventos_creados} · ${n.cc_creadas}.`}),t()},ne=async()=>{if(!i||!window.confirm(s.confirmCleanExtDemo))return;M(!0);const o=await nt(i);if(M(!1),o.error){x({title:s.extDemoCleanFailed,description:o.error,variant:"destructive"});return}x({title:s.extDemoCleaned,description:`${o.procesos} · ${o.rodeos} · ${o.lotes} · ${o.eventos} · ${o.cc}.`}),t()},E=async()=>{if(!(h!=null&&h.id)||!i){x({title:s.missingActiveFarm,variant:"destructive"});return}R(!0);const n=await lt(i,h.id);if(R(!1),n.error){x({title:s.demoFailed,description:n.error,variant:"destructive"});return}if(n.ya_existian){x({title:s.demoExists,description:s.demoExistsDesc}),t();return}x({title:s.demoLoaded,description:`${n.creados} · ${n.rodeos_creados}.`}),t()},U=p.useMemo(()=>{const n=[];for(const o of a){if(o.semaforo.sanidad!=="verde"){const r=o.riesgo_principal??(o.semaforo.sanidad==="rojo"?s.healthExpired:s.healthUpcoming),m=/^(\d+)/.exec(r),j=m?parseInt(m[1],10):void 0,v=m?r.replace(/^\d+\s*/,"").replace(/\(s\)/g,"").trim():r,S=o.semaforo.sanidad==="rojo"?"urgent":"warning",G=Ae({domain:"sanidad",focus:S,ctxCount:j,ctxLabel:v,source:"centro_op"});n.push({id:`${o.id}-tc-san`,proceso_id:o.id,proceso_nombre:o.nombre,tipo:"sanidad",severidad:o.semaforo.sanidad,titulo:r,detalle:`${o.nombre} · ${o.cabezas} ${s.headPrefix}`,cta_label:s.ctaResolve,cta_href:`/dashboard/proceso-productivo/procesos/${o.id}?${new URLSearchParams(G).toString()}`,vence_en_dias:0})}if(o.semaforo.condicion_corporal!=="verde"){const r=o.riesgo_principal??s.ccBelowTarget,m=o.semaforo.condicion_corporal==="rojo"?"urgent":"warning",j=Ae({domain:"cc",focus:m,ctxLabel:r,source:"centro_op"});n.push({id:`${o.id}-tc-cc`,proceso_id:o.id,proceso_nombre:o.nombre,tipo:"reproduccion",severidad:o.semaforo.condicion_corporal,titulo:r,detalle:`${o.nombre} · ${o.cabezas} ${s.headPrefix}`,cta_label:o.semaforo.condicion_corporal==="rojo"?s.ctaResolve:s.ctaView,cta_href:`/dashboard/proceso-productivo/procesos/${o.id}?${new URLSearchParams(j).toString()}`,vence_en_dias:0})}}return n.sort((o,r)=>Se[o.severidad]-Se[r.severidad])},[a,s]),Q=p.useMemo(()=>{const n=[];for(const o of a)if(o.proximo_hito){const r=new Date;r.setDate(r.getDate()+o.proximo_hito.en_dias),n.push({id:`${o.id}-hito`,proceso_id:o.id,fecha:r.toISOString().slice(0,10),titulo:`${o.proximo_hito.titulo} · ${o.nombre}`,estado:o.proximo_hito.en_dias<=7?"proximo":"futuro"})}return n.sort((o,r)=>o.fecha.localeCompare(r.fecha)).slice(0,6)},[a]),[I,z]=p.useState(()=>{if(typeof window>"u")return{...ge};try{const n=window.localStorage.getItem(Xe);if(!n)return{...ge};const o=JSON.parse(n);return{criticos:typeof o.criticos=="boolean"?o.criticos:ge.criticos,atencion:typeof o.atencion=="boolean"?o.atencion:ge.atencion,normal:typeof o.normal=="boolean"?o.normal:ge.normal}}catch{return{...ge}}}),f=n=>{z(o=>{const r={...o,[n]:!o[n]};try{window.localStorage.setItem(Xe,JSON.stringify(r))}catch{}return r})},y=p.useMemo(()=>{const n={criticos:[],atencion:[],normal:[]};for(const r of a)r.riesgo==="alto"?n.criticos.push(r):r.riesgo==="medio"?n.atencion.push(r):n.normal.push(r);const o=(r,m)=>{var S,G;const j=((S=r.proximo_hito)==null?void 0:S.en_dias)??Number.POSITIVE_INFINITY,v=((G=m.proximo_hito)==null?void 0:G.en_dias)??Number.POSITIVE_INFINITY;return j-v};return n.criticos.sort((r,m)=>Ze(m.riesgo_principal)-Ze(r.riesgo_principal)),n.atencion.sort(o),n.normal.sort(o),n},[a]),_=p.useMemo(()=>{const n=a.filter(v=>v.semaforo.sanidad==="rojo").length,o=a.filter(v=>v.semaforo.sanidad==="amarillo").length,r=a.filter(v=>v.semaforo.condicion_corporal==="rojo").length,m=a.filter(v=>v.semaforo.condicion_corporal==="amarillo").length,j=a.filter(v=>v.tipo==="feedlot"||v.tipo==="terminacion").length;return{sanRojos:n,sanAmarillos:o,ccRojos:r,ccAmarillos:m,engorde:j}},[a]),q=p.useMemo(()=>{const n=[];for(const o of a)o.semaforo.sanidad!=="verde"&&n.push({id:`${o.id}-rs`,proceso_id:o.id,proceso_nombre:o.nombre,dominio:"sanitario",severidad:o.semaforo.sanidad,titulo:s.riskHealth,detalle:o.riesgo_principal??s.riskHealthDetail,impacto_estimado:null,cta_href:`/dashboard/proceso-productivo/procesos/${o.id}?tab=sanidad`}),o.semaforo.condicion_corporal!=="verde"&&n.push({id:`${o.id}-rcc`,proceso_id:o.id,proceso_nombre:o.nombre,dominio:"reproductivo",severidad:o.semaforo.condicion_corporal,titulo:s.riskReproductive,detalle:o.riesgo_principal??s.riskReproductiveDetail,impacto_estimado:null,cta_href:`/dashboard/proceso-productivo/procesos/${o.id}?tab=cc`});return n.sort((o,r)=>Se[o.severidad]-Se[r.severidad])},[a,s]);if(A){const n=()=>H(A),o=A==="sanidad"?s.vistaSanidadTitle:A==="cc"?s.vistaCcTitle:A==="protocolos"?s.vistaProtocolosTitle:s.vistaEngordeTitle;return e.jsxs("div",{className:"space-y-6 max-w-7xl",children:[e.jsxs("div",{className:"flex items-center justify-between gap-3",children:[e.jsxs("div",{className:"flex items-center gap-2 text-xs text-muted-foreground",children:[e.jsxs("button",{type:"button",onClick:n,className:"hover:text-foreground flex items-center gap-1",children:[e.jsx(He,{className:"h-3 w-3"}),s.breadcrumb]}),e.jsx("span",{children:"/"}),e.jsx("span",{className:"text-foreground",children:o})]}),e.jsxs(C,{variant:"outline",size:"sm",onClick:n,children:[e.jsx(ht,{className:"h-3.5 w-3.5 mr-1"}),s.backToCenter]})]}),A==="sanidad"&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{children:[e.jsxs("h1",{className:"text-2xl font-bold text-foreground flex items-center gap-2",children:[e.jsx(Ie,{className:"h-6 w-6 text-primary"}),s.vistaSanidadTitle]}),e.jsx("p",{className:"text-muted-foreground text-sm",children:s.vistaSanidadSubtitle})]}),e.jsx(us,{})]}),A==="cc"&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{children:[e.jsxs("h1",{className:"text-2xl font-bold text-foreground flex items-center gap-2",children:[e.jsx(ke,{className:"h-6 w-6 text-primary"}),s.vistaCcTitle]}),e.jsx("p",{className:"text-muted-foreground text-sm",children:s.vistaCcSubtitle})]}),e.jsx(_t,{})]}),A==="protocolos"&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{children:[e.jsxs("h1",{className:"text-2xl font-bold text-foreground flex items-center gap-2",children:[e.jsx(qe,{className:"h-6 w-6 text-primary"}),s.vistaProtocolosTitle]}),e.jsx("p",{className:"text-muted-foreground text-sm",children:s.vistaProtocolosSubtitle})]}),e.jsx(Ut,{})]}),A==="engorde"&&e.jsx(ot,{})]})}return e.jsxs("div",{className:"space-y-6 max-w-7xl",children:[e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{children:[e.jsxs("h1",{className:"text-2xl font-bold text-foreground flex items-center gap-2",children:[e.jsx(He,{className:"h-6 w-6 text-primary"}),s.title]}),e.jsx("p",{className:"text-muted-foreground text-sm",children:s.subtitle})]}),e.jsxs("div",{className:"flex flex-wrap gap-2",children:[e.jsxs(C,{variant:A==="sanidad"?"default":"outline",size:"sm",onClick:()=>H("sanidad"),children:[e.jsx(Ie,{className:"h-4 w-4 mr-1"}),s.sanidadBtn,_.sanRojos+_.sanAmarillos>0&&e.jsx(F,{variant:"outline",className:`ml-1.5 text-[9px] h-4 px-1 ${_.sanRojos>
10?"bg-red-500/15 text-red-600 border-red-500/40":"bg-amber-500/15 text-amber-600 border-amber-500/40"}`,children:_.sanRojos+_.sanAmarillos})]}),e.jsxs(C,{variant:A==="cc"?"default":"outline",size:"sm",onClick:()=>H("cc"),children:[e.jsx(ke,{className:"h-4 w-4 mr-1"}),s.ccBtn,_.ccRojos+_.ccAmarillos>0&&e.jsx(F,{variant:"outline",className:`ml-1.5 text-[9px] h-4 px-1 ${_.ccRojos>0?"bg-red-500/15 text-red-600 border-red-500/40":"bg-amber-500/15 text-amber-600 border-amber-500/40"}`,children:_.ccRojos+_.ccAmarillos})]}),e.jsxs(C,{variant:A==="engorde"?"default":"outline",size:"sm",onClick:()=>H("engorde"),children:[e.jsx(gt,{className:"h-4 w-4 mr-1"}),s.engordeBtn,_.engorde>0&&e.jsx(F,{variant:"outline",className:"ml-1.5 text-[9px] h-4 px-1",children:_.engorde})]}),e.jsxs(C,{variant:A==="protocolos"?"default":"outline",size:"sm",onClick:()=>H("protocolos"),children:[e.jsx(qe,{className:"h-4 w-4 mr-1"}),s.protocolosBtn]}),e.jsx(C,{asChild:!0,variant:"outline",size:"sm",children:e.jsx(te,{to:"/dashboard/proceso-productivo/procesos",children:s.verProcesos})}),e.jsx(C,{asChild:!0,size:"sm",children:e.jsxs(te,{to:"/dashboard/proceso-productivo/procesos/nuevo",children:[e.jsx(fe,{className:"h-4 w-4 mr-1"}),s.nuevoProceso]})})]})]}),e.jsx(re,{className:"shadow-card border-primary/20",children:e.jsxs(W,{className:"p-4 space-y-3",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("h2",{className:"text-sm font-bold uppercase tracking-widest text-muted-foreground flex items-center gap-2",children:[e.jsx(ve,{className:"h-4 w-4 text-primary"}),s.whatToDoToday]}),e.jsxs(F,{className:"bg-primary/15 text-primary border-primary/30",children:[U.length," ",U.length===1?s.criticalTaskSingular:s.criticalTaskPlural]})]}),U.length===0?e.jsx("p",{className:"text-sm text-muted-foreground italic",children:s.noUrgent}):e.jsx("div",{className:"space-y-2",children:U.map(n=>e.jsx(dt,{tarea:n},n.id))})]})}),e.jsxs("section",{className:"space-y-3",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("h2",{className:"text-sm font-bold uppercase tracking-widest text-muted-foreground flex items-center gap-2",children:[e.jsx(ss,{className:"h-4 w-4 text-primary"}),s.cyclesState]}),e.jsxs(te,{to:"/dashboard/proceso-productivo/procesos",className:"text-xs text-primary hover:underline flex items-center gap-1",children:[s.viewAll," ",e.jsx(be,{className:"h-3 w-3"})]})]}),l&&e.jsx("div",{className:"text-xs text-muted-foreground italic",children:s.loadingCycles}),!l&&a.length===0&&e.jsx(re,{className:"shadow-card",children:e.jsxs(W,{className:"p-6 text-center text-sm text-muted-foreground space-y-3",children:[e.jsx("p",{children:s.emptyNoCycles}),e.jsx("p",{className:"text-xs",children:s.emptyDemoHint}),e.jsxs("div",{className:"flex flex-wrap gap-2 justify-center pt-1",children:[e.jsx(C,{size:"sm",variant:"outline",onClick:E,disabled:b,children:b?e.jsxs(e.Fragment,{children:[e.jsx(oe,{className:"h-4 w-4 mr-1 animate-spin"})," ",s.seeding]}):e.jsxs(e.Fragment,{children:[e.jsx(ve,{className:"h-4 w-4 mr-1"})," ",s.loadDemoData]})}),e.jsx(C,{asChild:!0,size:"sm",children:e.jsxs(te,{to:"/dashboard/proceso-productivo/procesos/nuevo",children:[e.jsx(fe,{className:"h-4 w-4 mr-1"})," ",s.createFirstCycle]})})]})]})}),a.length>0&&e.jsx("div",{className:"space-y-3",children:["criticos","atencion","normal"].map(n=>{const o=qt[n],r=y[n],m=I[n];return e.jsx(Gt,{groupKey:n,meta:o,procesos:r,collapsed:m,onToggle:()=>f(n)},n)})})]}),e.jsx(re,{className:"shadow-card",children:e.jsxs(W,{className:"p-4 space-y-3",children:[e.jsx("div",{className:"flex items-center justify-between",children:e.jsxs("h2",{className:"text-sm font-bold uppercase tracking-widest text-muted-foreground flex items-center gap-2",children:[e.jsx(ft,{className:"h-4 w-4 text-primary"}),s.upcomingMilestones]})}),e.jsx(mt,{hitos:Q})]})}),e.jsxs("section",{className:"space-y-3",children:[e.jsxs("h2",{className:"text-sm font-bold uppercase tracking-widest text-muted-foreground flex items-center gap-2",children:[e.jsx(jt,{className:"h-4 w-4 text-primary"}),s.productiveRisks]}),e.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-3 items-stretch",children:q.map(n=>{const o=n.severidad==="rojo"?"border-red-500/40 bg-red-500/5":n.severidad==="amarillo"?"border-amber-500/40 bg-amber-500/5":"border-emerald-500/40 bg-emerald-500/5";return e.jsx(re,{className:`border ${o} flex flex-col h-full`,children:e.jsxs(W,{className:"p-4 space-y-3 flex flex-col flex-1",children:[e.jsxs("div",{className:"flex items-start justify-between gap-2",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsxs("h3",{className:"font-semibold text-foreground flex items-center gap-2",children:[e.jsx("span",{"aria-hidden":!0,
1children:Ht[n.dominio]}),n.titulo]}),e.jsx("p",{className:"text-xs text-muted-foreground truncate",children:n.proceso_nombre})]}),e.jsx(xt,{value:n.severidad})]}),e.jsx("p",{className:"text-sm text-foreground",children:n.detalle}),n.impacto_estimado&&e.jsxs("p",{className:"text-[11px] italic text-muted-foreground",children:[s.estimatedImpact,": ",n.impacto_estimado]}),e.jsx(C,{asChild:!0,size:"sm",variant:"outline",className:"w-full mt-auto",children:e.jsxs(te,{to:n.cta_href,children:[s.viewActions,e.jsx(be,{className:"h-3 w-3 ml-1"})]})})]})},n.id)})})]}),e.jsxs("section",{className:"space-y-2",children:[e.jsxs("h2",{className:"text-sm font-bold uppercase tracking-widest text-muted-foreground flex items-center gap-2",children:[e.jsx(ve,{className:"h-4 w-4 text-primary"}),s.healthCampaigns]}),e.jsx(re,{className:"shadow-card border-dashed",children:e.jsxs(W,{className:"p-4 flex items-start gap-3",children:[e.jsx("div",{className:"h-9 w-9 rounded-md bg-muted/50 flex items-center justify-center shrink-0",children:e.jsx(ve,{className:"h-4 w-4 text-muted-foreground"})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("p",{className:"text-sm font-semibold text-foreground",children:s.campaignsComingSoon}),e.jsxs("p",{className:"text-[11px] text-muted-foreground mt-0.5",children:[s.campaignsDescPre,e.jsx(te,{to:"/dashboard/proceso-productivo/sanidad",className:"text-primary hover:underline",children:s.campaignsLink}),"."]})]})]})})]}),e.jsx(re,{className:"shadow-card border-dashed border-amber-500/30 bg-amber-500/5",children:e.jsxs(W,{className:"p-4 space-y-3",children:[e.jsxs("div",{className:"flex items-start gap-2",children:[e.jsx(vt,{className:"h-4 w-4 text-amber-600 mt-0.5"}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("h3",{className:"text-sm font-semibold text-amber-700 dark:text-amber-400",children:s.demoDataTitle}),e.jsxs("p",{className:"text-[11px] text-muted-foreground",children:[s.demoDataDescPre,e.jsx("code",{children:"[DEMO]"}),s.demoDataDescPost,e.jsx("code",{children:"supabase/seeds/protocolos_sanitarios.sql"}),s.demoDataDescEnd]})]})]}),e.jsxs("div",{className:"flex flex-wrap gap-2",children:[e.jsx(C,{size:"sm",variant:"outline",onClick:O,disabled:$||L,children:$?e.jsxs(e.Fragment,{children:[e.jsx(oe,{className:"h-3.5 w-3.5 mr-1 animate-spin"})," ",s.seeding]}):e.jsxs(e.Fragment,{children:[e.jsx(ve,{className:"h-3.5 w-3.5 mr-1"})," ",s.seedExtendedDemo]})}),e.jsx(C,{size:"sm",variant:"outline",onClick:ne,disabled:$||L,children:L?e.jsxs(e.Fragment,{children:[e.jsx(oe,{className:"h-3.5 w-3.5 mr-1 animate-spin"})," ",s.cleaning]}):e.jsxs(e.Fragment,{children:[e.jsx(as,{className:"h-3.5 w-3.5 mr-1"})," ",s.cleanExtendedDemo]})}),e.jsx(C,{size:"sm",variant:"ghost",onClick:E,disabled:b,children:b?e.jsxs(e.Fragment,{children:[e.jsx(oe,{className:"h-3.5 w-3.5 mr-1 animate-spin"})," ",s.seeding]}):e.jsx(e.Fragment,{children:s.basicDemo})})]})]})}),e.jsxs("p",{className:"text-[11px] text-muted-foreground italic",children:[s.previewNotePre,e.jsx("code",{children:"[DEMO]"}),s.previewNotePost]})]})},Gt=({groupKey:a,meta:l,procesos:t,collapsed:h,onToggle:i})=>{const{t:x}=ie(),d=x.procesoProductivo.centroOperativo,s=t.length;return e.jsxs(re,{className:"shadow-card overflow-hidden",children:[e.jsxs("button",{type:"button",onClick:i,"aria-expanded":!h,className:ae("w-full flex items-center gap-2.5 px-4 py-3 text-left transition-colors",l.bg,"hover:brightness-95"),children:[h?e.jsx(Ve,{className:ae("h-4 w-4",l.text)}):e.jsx(Me,{className:ae("h-4 w-4",l.text)}),e.jsx("span",{className:ae("h-2.5 w-2.5 rounded-full",l.dot)}),e.jsx("span",{className:ae("text-sm font-semibold",l.text),children:d[l.labelKey]}),e.jsx("span",{className:ae("ml-auto text-[11px] font-medium px-2 py-0.5 rounded-full",l.badgePill),children:s})]}),!h&&s>0&&e.jsx(W,{className:"p-4 border-t border-border",children:e.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 xl:grid-cols-3 gap-4 items-stretch",children:t.map(b=>e.jsx(Wt,{proceso:b,grupo:a,meta:l},b.id))})}),!h&&s===0&&e.jsx(W,{className:"px-4 py-6 border-t border-border text-center",children:e.jsx("p",{className:"text-xs text-muted-foreground italic",children:a==="criticos"?d.emptyCriticos:a==="atencion"?d.emptyAtencion:d.emptyNormal})})]})},Wt=({proceso:a,grupo:l,meta:t})=>{const{t:h}=ie(),i=h.procesoProductivo.centroOperativo,x=h.procesoProductivo.shared,d=()=>{let s="sanidad";a.semaforo.sanidad==="rojo"?s="sanidad":a.semaforo.condicion_corporal==="rojo"?s="cc":a.semaforo.sanidad==="amarillo"?s="sanidad":a.semaforo.condicion_corporal==="amarillo"&&(s="cc");const b=Ae({domain:s,focus:l==="criticos"?"urgent":"warning",ctxLabel:a.riesgo_principal??void 0,source:"centro_op"});return`/dashboard/proceso-productivo/procesos/${a.id}?${new URLSearchParams(b).toString()}`};return e.jsx(re,{className:ae("shadow-card hover:shadow-md transition-shadow flex flex-col h-full","border-l-4",t.border),children:e.jsxs(W,{className:"p-4 space-y-3 flex flex-col flex-1",children:[e.jsxs("div",{className:"min-w-0 space-y-1",children:[e.jsxs("div",{className:"flex items-center gap-1.5 flex-wrap",children:[e.jsx(F,{variant:"outline",className:"text-[10px] font-mono tracking-tight",children:a.id_interno}),e.jsx(F,{variant:"outline",className:"text-[10px]",children:x.tipos[a.tipo]}),e.jsx(F,{variant:"outline",className:`text-[10px] ${pt[a.estado]}`,children:x.estados[a.estado]})]}),e.jsx("h3",{className:"font-semibold text-foreground truncate",children:a.nombre}),e.jsxs("p",{className:"text-[11px] text-muted-foreground",children:[a.cabezas," ",i.headPrefix," · ",a.rodeo_nombre," · ",a.mercado]})]}),e.jsx(ut,{actual:a.dia_actual,total:a.dia_total}),l==="criticos"&&a.riesgo_principal&&e.jsx("div",{className:"rounded-md bg-red-500/10 border border-red-500/20 px-2.5 py-2",children:e.jsxs("p",{className:"text-[11px] font-medium text-red-700 dark:text-red-400 flex items-start gap-1.5",children:[e.jsx(me,{className:"h-3.5 w-3.5 shrink-0 mt-0.5"}),e.jsx("span",{className:"leading-snug",children:a.riesgo_principal})]})}),l==="atencion"&&a.riesgo_principal&&e.jsx("div",{className:"rounded-md bg-amber-500/10 border border-amber-500/20 px-2.5 py-2",children:e.jsxs("p",{className:"text-[11px] font-medium text-amber-700 dark:text-amber-400 flex items-start gap-1.5",children:[e.jsx(me,{className:"h-3.5 w-3.5 shrink-0 mt-0.5"}),e.jsx("span",{className:"leading-snug",children:a.riesgo_principal})]})}),l==="normal"&&e.jsxs("p",{className:"text-[11px] text-emerald-700 dark:text-emerald-400 flex items-center gap-1.5",children:[e.jsx($e,{className:"h-3.5 w-3.5 shrink-0"}),i.noActiveAlerts]}),e.jsxs("div",{className:"text-xs",children:[e.jsx("p",{className:"text-[10px] uppercase tracking-wider text-muted-foreground",children:i.nextMilestone}),a.proximo_hito?e.jsxs("p",{className:"font-medium text-foreground leading-snug",children:[a.proximo_hito.titulo,e.jsxs("span",{className:"text-muted-foreground font-normal ml-1",children:["— ",i.inDaysPrefix," ",a.proximo_hito.en_dias," ",a.proximo_hito.en_dias===1?i.daySingular:i.dayPlural]})]}):e.jsx("p",{className:"text-muted-foreground italic",children:i.noUpcomingMilestones})]}),l==="criticos"?e.jsx(C,{asChild:!0,size:"sm",className:"w-full mt-auto bg-red-600 hover:bg-red-700 text-white",children:e.jsxs(te,{to:d(),children:[e.jsx(bt,{className:"h-3.5 w-3.5 mr-1"}),i.resolveBtn]})}):l==="atencion"?e.jsx(C,{asChild:!0,size:"sm",className:"w-full mt-auto bg-amber-600 hover:bg-amber-700 text-white",children:e.jsxs(te,{to:d(),children:[e.jsx(Ps,{className:"h-3.5 w-3.5 mr-1"}),i.prepareBtn]})}):e.jsx(C,{asChild:!0,size:"sm",variant:"outline",className:"w-full mt-auto",children:e.jsxs(te,{to:`/dashboard/proceso-productivo/procesos/${a.id}`,children:[i.viewOpsCenter,e.jsx(be,{className:"h-3.5 w-3.5 ml-1"})]})})]})})};export{Tr 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.