PageSourceSearch

https://radreport.com.br/assets/TemplatesPage-D0pyahmC.js

js radreport.com.br collected 2026-09-24 14:36:04 UTC 45,601 bytes, 31 lines download raw bytes

1import{j as e,u as ke,k as as}from"./vendor-query-skQMsM6X.js";import{r as d}from"./vendor-react-DyYvSSk1.js";import{aq as i,aK as ts,p as x,aQ as os,ah as rs,c as g,aL as te,I as A,a6 as is,a8 as ls,T as ns,aR as Fe,a9 as cs,bj as ds,r as $,v as B,x as J,y as H,z as p,aJ as ms,ab as R,am as Ne,an as be,ao as ye,ap as Ce,aM as xs,aN as us,aO as ee,aP as se,as as we,b as q,X as hs}from"./index-BGwtrXIa.js";import{u as ps}from"./useDebounce-kVyuRpVJ.js";import{T as ae}from"./textarea-ChvLdc2s.js";import{T as gs,a as js,b as _e,c as L,d as fs,e as P}from"./table-DnRDtd-j.js";import{C as Pe,a as Ie,b as qe}from"./collapsible-CSslgSh4.js";import{n as vs,g as Ns,i as Te,c as ge,p as bs,a as ie,b as ys,d as Cs}from"./templateVariableProcessor-BxWBf8HQ.js";import{d as je}from"./templateFormatter-CtNPpNn7.js";import{c as ws,a as Se,bu as _s,ae as Le,F as Je,u as Ae,ak as Ts,b1 as He,aK as Ss,bx as ze,aa as As,ag as Es,Y as Ms,aR as Rs,o as Vs,c3 as Os,L as De,bq as $e,X as ks,br as Fs,bg as Ps,bH as Is,bp as qs}from"./vendor-ui-CCmu0bzQ.js";import{p as Be}from"./pt-BR-0bEujIJO.js";import{p as Ls}from"./parse-CtdOddQZ.js";import{R as zs,a as Ds,b as $s,c as Bs}from"./RevisionHistoryTab-IjPlKLlA.js";import"./vendor-supabase-BfoV2C50.js";function Js({formData:n,tecnicaConfigForm:y}){const[_,E]=d.useState([]),[C,G]=d.useState({}),[K,oe]=d.useState({}),[U,fe]=d.useState(!0),[X,ne]=d.useState(!0),[b,M]=d.useState([]),T=d.useMemo(()=>n.tecnica?typeof n.tecnica=="object"&&!Array.isArray(n.tecnica)?n.tecnica:{}:{},[n.tecnica]),w=d.useMemo(()=>Object.keys(T),[T]),z=w.length>1,S=d.useMemo(()=>vs(n.variaveis),[n.variaveis]),j=d.useMemo(()=>y.tipo!=="auto"?y:Ns(T),[y,T]);d.useEffect(()=>{if(j.tipo==="complementar")E(w);else{const r=w.includes("SEM")?"SEM":w[0]||"";E(r?[r]:[])}const s={},o={};S.forEach(r=>{r.valor_padrao!==void 0&&r.valor_padrao!==null&&(s[r.nome]=r.valor_padrao),Te(r)&&(o[r.nome]=ge())}),G(s),oe(o),M([])},[n,S,w,j.tipo]);const W=d.useMemo(()=>{if(!n.achados&&!n.impressao)return[];const s=bs(n.condicoes_logicas,C),o=ie(n.achados||"",s),r=ie(n.impressao||"",s),f=n.adicionais?ie(n.adicionais,s):"";let k="";j.tipo==="complementar"?k=(j.ordem_exibicao||w).filter(v=>T[v]).map(v=>{const I=ie(T[v],s);return j.prefixo_label?`${v.charAt(0).toUpperCase()+v.slice(1).toLowerCase()}: ${I}`:I}).join(j.separador||". "):k=_.map(u=>T[u]).filter(Boolean).map(u=>ie(u,s)).join(j.separador||" ");const c=[];return c.push({id:"titulo",label:"Título",html:`<h2 style="text-align: center; text-transform: uppercase; font-weight: bold; margin-bottom: 12pt;">${n.titulo||"TÍTULO DO TEMPLATE"}</h2>`}),k&&c.push({id:"tecnica",label:"Técnica",html:`<h3 style="text-transform: uppercase; font-weight: bold; margin-top: 18pt; margin-bottom: 8pt;">TÉCNICA</h3>${je(k)}`}),c.push({id:"achados",label:"Achados",html:`<h3 style="text-transform: uppercase; font-weight: bold; margin-top: 18pt; margin-bottom: 8pt;">ACHADOS</h3>${je(o)}`}),c.push({id:"impressao",label:"Impressão",html:`<h3 style="text-transform: uppercase; font-weight: bold; margin-top: 18pt; margin-bottom: 8pt;">IMPRESSÃO</h3>${je(r)}`}),f&&c.push({id:"adicionais",label:"Adicionais",html:`<h3 style="text-transform: uppercase; font-weight: bold; margin-top: 18pt; margin-bottom: 8pt;">ADICIONAIS</h3>${je(f)}`}),c},[n,_,C,T,w,j]),Y=d.useMemo(()=>W.filter(s=>!b.includes(s.id)).map(s=>s.html).join(""),[W,b]),l=s=>{M(o=>o.includes(s)?o.filter(r=>r!==s):[...o,s])},V=(s,o)=>{G(r=>({...r,[s]:o}))},O=(s,o,r)=>{oe(f=>{const c={...f[s]||ge(),[o]:r},u=Cs(c);return G(m=>({...m,[s]:u})),{...f,[s]:c}})},ce=()=>{if(j.tipo==="complementar")E(w);else{const r=w.includes("SEM")?"SEM":w[0]||"";E(r?[r]:[])}const s={},o={};S.forEach(r=>{r.valor_padrao!==void 0&&r.valor_padrao!==null&&(s[r.nome]=r.valor_padrao),Te(r)&&(o[r.nome]=ge())}),G(s),oe(o),M([]),g.info("Preview resetado")},Q=()=>{const s=S.filter(o=>o.obrigatorio&&(C[o.nome]===void 0||C[o.nome]==="")).map(o=>o.descricao||o.nome);if(s.length>0){g.warning(`Campos obrigatórios pendentes: ${s.join(", ")}`);return}g.success("Template funcionando corretamente! Pronto para salvar.",{description:`${S.length} variáveis processadas, ${W.filter(o=>!b.includes(o.id)).length} seções incluídas`})},D=s=>{var r,f,k;const o=C[s.nome];if(s.tipo==="volume"||Te(s)){const c=K[s.nome]||ge(),u=ys(c.x,c.y,c.z),m=c.useCalculated?u:c.directVolume;return e.jsxs("div",{className:"space-y-3 p-4 rounded-lg border border-border bg-muted/30",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs(i,{className:"text-sm font-medium",children:[s.descricao||s.nome,e.jsxs("span",{className:"text-muted-foreground ml-1",children:["(",s.unidade||"cm³",")"]}),s.obrigatorio&&e.jsx("span",{className:"text-destructive ml-1",children:"*"})]}),e.jsxs("div",{className:"flex items-center gap-2 text-xs",children:[e.jsx(Ss,{className:"h-3.5 w-3.5 text-muted-foreground"}),e.jsx("span",{className:c.useCalculated?"text-blue-500 font-medium":"text-muted-foreground",children:"Medidas"}),e.jsx(te,{checked:!c.useCalculated,onCheckedChange:v=>O(s.nome,"useCalculated",!v),className:"h-4 w-7"}),e.jsx("span",{className:c.useCalculated?"text-muted-foreground":"text-blue-500 font-medium",children:"Direto"}),e.jsx(ze,{className:"h-3.5 w-3.5 text-muted-foreground"})]})]}),c.useCalculated?e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"grid grid-cols-3 gap-2",children:[e.jsxs("div",{children:[e.jsx(i,{className:"text-xs text-muted-foreground",children:"X (cm)"}),e.jsx(A,{type:"number",step:"0.1",min:"0",value:c.x||"",onChange:v=>O(s.nome,"x",parseFloat(v.target.value)||0),placeholder:"0,0",className:"h-8 text-sm"})]}),e.jsxs("div",{children:[e.jsx(i,{className:"text-xs text-muted-foreground",children:"Y (cm)"}),e.jsx(A,{type:"number",step:"0.1",min:"0",value:c.y||"",onChange:v=>O(s.nome,"y",parseFloat(v.target.value)||0),placeholder:"0,0",className:"h-8 text-sm"})]}),e.jsxs("div",{children:[e.jsx(i,{className:"text-xs text-muted-foreground",children:"Z (cm)"}),e.jsx(A,{type:"number",step:"0.1",min:"0",value:c.z||"",onChange:v=>O(s.nome,"z",parseFloat(v.target.value)||0),placeholder:"0,0",className:"h-8 text-sm"})]})]}),e.jsxs("p",{className:"text-xs text-muted-foreground flex items-center gap-1",children:[e.jsx(ze,{className:"h-3 w-3"}),"Fórmula elipsoide: L × W × H × 0,52 =",e.jsxs("span",{className:"font-semibold text-blue-500",children:[u.toLocaleStr
1ing("pt-BR",{minimumFractionDigits:1,maximumFractionDigits:1})," cm³"]})]})]}):e.jsxs("div",{className:"space-y-2",children:[e.jsx(A,{type:"number",step:"0.1",min:"0",value:c.directVolume||"",onChange:v=>O(s.nome,"directVolume",parseFloat(v.target.value)||0),placeholder:"0,0"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Volume informado pelo equipamento ou medido diretamente"})]}),e.jsxs("div",{className:"flex items-center justify-between pt-2 border-t border-border",children:[e.jsx("span",{className:"text-sm text-muted-foreground",children:"Volume final:"}),e.jsxs("span",{className:"text-lg font-bold text-blue-500",children:[m.toLocaleString("pt-BR",{minimumFractionDigits:1,maximumFractionDigits:1})," ",s.unidade||"cm³"]})]})]},s.nome)}switch(s.tipo){case"texto":return e.jsxs("div",{className:"space-y-2",children:[e.jsxs(i,{htmlFor:s.nome,children:[s.descricao||s.nome,s.obrigatorio&&e.jsx("span",{className:"text-destructive ml-1",children:"*"})]}),e.jsx(A,{id:s.nome,value:(o==null?void 0:o.toString())||"",onChange:m=>V(s.nome,m.target.value),placeholder:((r=s.valor_padrao)==null?void 0:r.toString())||""})]},s.nome);case"numero":return e.jsxs("div",{className:"space-y-2",children:[e.jsxs(i,{htmlFor:s.nome,children:[s.descricao||s.nome,s.unidade&&e.jsxs("span",{className:"text-muted-foreground ml-1",children:["(",s.unidade,")"]}),s.obrigatorio&&e.jsx("span",{className:"text-destructive ml-1",children:"*"}),(s.minimo!==void 0||s.maximo!==void 0)&&e.jsxs("span",{className:"text-xs text-muted-foreground ml-2",children:["[",s.minimo??"..."," - ",s.maximo??"...","]"]})]}),e.jsx(A,{id:s.nome,type:"number",min:s.minimo,max:s.maximo,step:"0.1",value:(o==null?void 0:o.toString())||"",onChange:m=>V(s.nome,parseFloat(m.target.value)||0),placeholder:((f=s.valor_padrao)==null?void 0:f.toString())||"0"})]},s.nome);case"select":return e.jsxs("div",{className:"space-y-2",children:[e.jsxs(i,{htmlFor:s.nome,children:[s.descricao||s.nome,s.obrigatorio&&e.jsx("span",{className:"text-destructive ml-1",children:"*"})]}),e.jsxs($,{value:(o==null?void 0:o.toString())||"",onValueChange:m=>V(s.nome,m),children:[e.jsx(B,{children:e.jsx(J,{placeholder:"Selecione uma opção"})}),e.jsx(H,{children:(k=s.opcoes)==null?void 0:k.map(m=>e.jsx(p,{value:m,children:m},m))})]})]},s.nome);case"boolean":return e.jsxs("div",{className:"flex items-center justify-between space-y-2",children:[e.jsx(i,{htmlFor:s.nome,children:s.descricao||s.nome}),e.jsx(te,{id:s.nome,checked:!!o,onCheckedChange:m=>V(s.nome,m)})]},s.nome);case"data":const c=o?Ls(o,"dd/MM/yyyy",new Date):void 0,u=c&&!isNaN(c.getTime());return e.jsxs("div",{className:"space-y-2",children:[e.jsxs(i,{htmlFor:s.nome,children:[s.descricao||s.nome,s.obrigatorio&&e.jsx("span",{className:"text-destructive ml-1",children:"*"})]}),e.jsxs(is,{children:[e.jsx(ls,{asChild:!0,children:e.jsxs(x,{variant:"outline",className:ns("w-full justify-start text-left font-normal",!u&&"text-muted-foreground"),children:[e.jsx(As,{className:"mr-2 h-4 w-4"}),u?Fe(c,"dd/MM/yyyy",{locale:Be}):"Selecione a data..."]})}),e.jsx(cs,{className:"w-auto p-0",align:"start",children:e.jsx(ds,{mode:"single",selected:u?c:void 0,onSelect:m=>{m&&V(s.nome,Fe(m,"dd/MM/yyyy"))},locale:Be,initialFocus:!0,className:"pointer-events-auto"})})]})]},s.nome);default:return null}};return n.achados||n.impressao?e.jsxs("div",{className:"space-y-4",children:[e.jsx("div",{className:"bg-amber-500/10 border border-amber-500/30 rounded-lg p-3",children:e.jsxs("p",{className:"text-sm text-amber-600 dark:text-amber-400 flex items-center gap-2",children:[e.jsx(Se,{className:"h-4 w-4 flex-shrink-0"}),e.jsxs("span",{children:[e.jsx("strong",{children:"Modo Simulação:"})," Este é exatamente como o radiologista verá o modal ao clicar no template."]})]})}),z&&j.tipo==="alternativo"&&e.jsxs("div",{className:"space-y-3",children:[e.jsx(i,{className:"text-base font-semibold",children:"TÉCNICA (selecione uma ou mais)"}),e.jsx("div",{className:"space-y-2",children:w.map(s=>e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(ts,{id:`tech-${s}`,checked:_.includes(s),onCheckedChange:o=>{E(o?r=>[...r,s]:r=>r.filter(f=>f!==s))}}),e.jsx(i,{htmlFor:`tech-${s}`,className:"cursor-pointer",children:s})]},s))})]}),z&&j.tipo==="complementar"&&e.jsxs("div",{className:"space-y-3",children:[e.jsx(i,{className:"text-base font-semibold",children:"TÉCNICA"}),e.jsx("div",{className:"text-sm bg-muted/30 p-3 rounded-lg space-y-1 border border-border/50",children:w.map(s=>e.jsxs("div",{className:"text-muted-foreground",children:[j.prefixo_label&&e.jsxs("span",{className:"font-medium text-foreground",children:[s.charAt(0).toUpperCase()+s.slice(1).toLowerCase(),":"]}
1)," ",e.jsx("span",{className:"text-foreground/80",children:T[s]})]},s))}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Campos complementares são concatenados automaticamente"})]}),S.length>0&&e.jsxs(Pe,{open:U,onOpenChange:fe,children:[e.jsxs(Ie,{className:"flex items-center justify-between w-full py-2 px-3 rounded-lg bg-muted/30 hover:bg-muted/50 transition-colors",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(_s,{className:"h-4 w-4 text-blue-500"}),e.jsx(i,{className:"text-base font-semibold cursor-pointer",children:"VARIÁVEIS"}),e.jsxs("span",{className:"text-xs text-muted-foreground bg-muted px-2 py-0.5 rounded-full",children:[Object.keys(C).filter(s=>C[s]!==void 0&&C[s]!=="").length,"/",S.length," preenchidas"]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[(()=>{const s=S.filter(o=>o.obrigatorio&&(C[o.nome]===void 0||C[o.nome]==="")).length;return s>0&&e.jsxs("span",{className:"text-xs bg-amber-500/20 text-amber-500 px-2 py-0.5 rounded-full",children:[s," obrigatória",s>1?"s":""," pendente",s>1?"s":""]})})(),e.jsx(Le,{className:`h-4 w-4 text-muted-foreground transition-transform duration-200 ${U?"rotate-180":""}`})]})]}),e.jsx(qe,{className:"mt-3",children:e.jsx("div",{className:"space-y-4",children:S.map(D)})})]}),S.length===0&&e.jsx("div",{className:"text-sm text-muted-foreground bg-muted/30 p-3 rounded-lg border border-border/50",children:"Este template não possui variáveis dinâmicas."}),e.jsxs(Pe,{open:X,onOpenChange:ne,children:[e.jsxs(Ie,{className:"flex items-center justify-between w-full py-2 px-3 rounded-lg bg-muted/30 hover:bg-muted/50 transition-colors",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Je,{className:"h-4 w-4 text-blue-500"}),e.jsx(i,{className:"text-base font-semibold cursor-pointer",children:"PREVIEW"}),b.length>0&&e.jsxs("span",{className:"text-xs bg-amber-500/20 text-amber-500 px-2 py-0.5 rounded-full",children:[b.length," seção removida",b.length>1?"s":""]})]}),e.jsx(Le,{className:`h-4 w-4 text-muted-foreground transition-transform duration-200 ${X?"rotate-180":""}`})]}),e.jsxs(qe,{className:"mt-3",children:[e.jsx("div",{className:"flex flex-wrap gap-2 mb-3",children:W.map(s=>e.jsx(x,{variant:b.includes(s.id)?"destructive":"outline",size:"sm",onClick:()=>l(s.id),className:"h-7 text-xs gap-1.5",children:b.includes(s.id)?e.jsxs(e.Fragment,{children:[e.jsx(Ae,{className:"h-3 w-3"}),s.label," (removida)"]}):s.label},s.id))}),e.jsx(os,{className:"h-[300px] w-full rounded-lg border border-border [&_[data-orientation=vertical]]:w-1.5 [&_[data-orientation=vertical]]:bg-transparent [&_[data-orientation=vertical]_>_div]:bg-blue-500/30 [&_[data-orientation=vertical]_>_div]:hover:bg-blue-500/50 [&_[data-orientation=vertical]_>_div]:rounded-full",children:e.jsx("div",{className:"p-4 bg-background prose prose-sm prose-invert max-w-none",style:{color:"hsl(var(--foreground))"},dangerouslySetInnerHTML:{__html:rs(Y)}})})]})]}),e.jsxs("div",{className:"flex gap-3 pt-4 border-t border-border",children:[e.jsxs(x,{variant:"outline",onClick:ce,className:"gap-2",children:[e.jsx(Ts,{className:"h-4 w-4"}),"Reset"]}),e.jsxs(x,{onClick:Q,className:"flex-1 gap-2 bg-blue-600 hover:bg-blue-700",children:[e.jsx(He,{className:"h-4 w-4"}),"Testar Aplicação"]})]})]}):e.jsxs("div",{className:"flex flex-col items-center justify-center py-12 text-center",children:[e.jsx(ws,{className:"h-12 w-12 text-muted-foreground/50 mb-4"}),e.jsx("p",{className:"text-lg font-medium text-muted-foreground",children:"Preencha Achados e/ou Impressão"}),e.jsx("p",{className:"text-sm text-muted-foreground/70 mt-1",children:'Adicione conteúdo na aba "Conteúdo" para ver o preview'})]})}const Hs=n=>{if(!n||typeof n!="object"||Array.isArray(n))return{tipo:"auto",concatenar:!0};const y=n;return{tipo:y.tipo||"auto",concatenar:y.concatenar!==!1,separador:typeof y.separador=="string"?y.separador:". ",prefixo_label:y.prefixo_label===!0,ordem_exibicao:Array.isArray(y.ordem_exibicao)?y.ordem_exibicao:void 0}},le=15,Us=(n,y)=>{if(n&&typeof n=="object"){const _=n;if(_.code==="PGRST116")return"Não foi possível confirmar o salvamento. Recarregue a página e tente novamente.";
1const E=[_.message,_.details,_.hint].filter(Boolean);if(E.length>0)return E.join(" — ")}return n instanceof Error?n.message:y};function la(){var Re,Ve;const[n,y]=d.useState(""),[_,E]=d.useState("all"),[C,G]=d.useState("all"),[K,oe]=d.useState("all"),[U,fe]=d.useState("all"),[X,ne]=d.useState("updated"),[b,M]=d.useState(1),T=ps(n,300),[w,z]=d.useState(!1),[S,j]=d.useState(!1),[W,Y]=d.useState(!1),[l,V]=d.useState(null),[O,ce]=d.useState(!1),[Q,D]=d.useState(null),de=d.useRef(!1),[s,o]=d.useState({codigo:"",titulo:"",modalidade_codigo:"",regiao_codigo:"",tecnica:{},achados:"",impressao:"",adicionais:"",conteudo_template:"",tags:[],ativo:!0,variaveis:[],condicoes_logicas:[],categoria:"normal",atalho:""}),[r,f]=d.useState({tipo:"auto",concatenar:!0}),[k,c]=d.useState("basico"),{data:u}=ke({queryKey:["admin-template-refs"],queryFn:async()=>{const[a,t]=await Promise.all([q.from("modalidades").select("id, codigo, nome").eq("ativa",!0).order("ordem"),q.from("regioes_anatomicas").select("id, codigo, nome").eq("ativa",!0).order("nome")]);return{modalidades:a.data||[],regioes:t.data||[]}},staleTime:5*6e4,refetchOnWindowFocus:!1}),m=(u==null?void 0:u.modalidades)??[],v=(u==null?void 0:u.regioes)??[],{data:I,isLoading:me,refetch:re}=ke({queryKey:["admin-templates",b,T,_,C,K,U,X],queryFn:async()=>{let a=q.from("system_templates").select("id, codigo, titulo, tags, modalidade_codigo, atalho, categoria, variaveis, updated_at, ativo",{count:"exact"});if(T){const pe=`%${T}%`;a=a.or(`titulo.ilike.${pe},codigo.ilike.${pe}`)}if(_!=="all"&&(a=a.eq("modalidade_codigo",_)),C!=="all"&&(a=a.eq("ativo",C==="active")),K!=="all"&&(a=a.eq("categoria",K)),U!=="all"){const pe=U==="today"?1:7,ss=new Date(Date.now()-pe*864e5).toISOString();a=a.gte("updated_at",ss)}const t=(b-1)*le,h=t+le-1,N=X==="updated"?a.order("updated_at",{ascending:!1}):a.order("modalidade_codigo").order("titulo"),{data:Ze,count:es,error:Oe}=await N.range(t,h);if(Oe)throw Oe;return{templates:Ze||[],totalCount:es||0}},staleTime:3e4,placeholderData:as}),Ee=(I==null?void 0:I.templates)??[],xe=(I==null?void 0:I.totalCount)??0,ue=Math.ceil(xe/le),ve=async a=>{const{data:t,error:h}=await q.from("system_templates").select("*").eq("id",a).maybeSingle();if(h)throw h;return t??null},Me=async a=>{D(a.id);try{const t=await ve(a.id);if(!t){g.error("Não foi possível carregar o template completo. Recarregue a página e tente novamente.");return}V(t),o({...t,tecnica:t.tecnica||{},variaveis:t.variaveis||[],condicoes_logicas:t.condicoes_logicas||[],atalho:t.atalho||""}),f(Hs(t.tecnica_config)),c("basico"),z(!0)}catch{g.error("Não foi possível carregar o template completo. Recarregue a página e tente novamente.")}finally{D(null)}},Ue=()=>{V(null),o({codigo:"",titulo:"",modalidade_codigo:"",regiao_codigo:"",tecnica:{},achados:"",impressao:"",adicionais:"",conteudo_template:"",tags:[],ativo:!0,variaveis:[],condicoes_logicas:[],categoria:"normal",atalho:""}),f({tipo:"auto",concatenar:!0}),c("basico"),z(!0)},Xe=async a=>{D(a.id);try{const t=await ve(a.id);if(!t){g.error("Não foi possível carregar o template completo. Recarregue a página e tente novamente.");return}V(t),j(!0)}catch{g.error("Não foi possível carregar o template completo. Recarregue a página e tente novamente.")}finally{D(null)}},Ge=a=>{V(a),Y(!0)},Ke=async a=>{D(a.id);try{const t=await ve(a.id);if(!t){g.error("Não foi possível carregar o template completo. Recarregue a página e tente novamente.");return}const h={codigo:`${t.codigo}_COPY`,titulo:`${t.titulo} (Cópia)`,modalidade_codigo:t.modalidade_codigo,regiao_codigo:t.regiao_codigo,tecnica:Z(t.tecnica),achados:F(t.achados),impressao:F(t.impressao),adicionais:F(t.adicionais)||null,conteudo_template:F(t.conteudo_template)||null,indicacao_clinica:F(t.indicacao_clinica)||null,tags:t.tags,ativo:t.ativo,variaveis:t.variaveis,condicoes_logicas:t.condicoes_logicas,categoria:t.categoria,tecnica_config:Z(t.tecnica_config)},{error:N}=await q.from("system_templates").insert(h);if(N)throw N;g.success("Template duplicado com sucesso"),re()}catch{g.error("Erro ao duplicar template")}finally{D(null)}},F=a=>
1a&&a.replace(/\\n\\n/g,`
2
3`).replace(/\\n/g,`
4`),Z=a=>{if(!a||typeof a!="object")return a;if(Array.isArray(a))return a.map(h=>Z(h));const t={};for(const[h,N]of Object.entries(a))typeof N=="string"?t[h]=N.replace(/\\n\\n/g,`
5
6`).replace(/\\n/g,`
7`):typeof N=="object"&&N!==null?t[h]=Z(N):t[h]=N;return t},We=async()=>{var a;if(!de.current)try{if(!s.codigo||!s.titulo||!s.modalidade_codigo||!s.achados||!s.impressao){g.error("Preencha os campos obrigatórios");return}de.current=!0,ce(!0);const t={codigo:s.codigo,titulo:s.titulo,modalidade_codigo:s.modalidade_codigo,regiao_codigo:s.regiao_codigo||null,tecnica:Z(s.tecnica),achados:F(s.achados),impressao:F(s.impressao),adicionais:F(s.adicionais)||null,conteudo_template:F(s.conteudo_template)||null,indicacao_clinica:F(s.indicacao_clinica)||null,tags:s.tags,ativo:s.ativo,variaveis:s.variaveis,condicoes_logicas:s.condicoes_logicas,categoria:s.categoria||"normal",tecnica_config:Z(r),atalho:((a=s.atalho)==null?void 0:a.toLowerCase().replace(/[^a-z0-9]/g,""))||null};if(l){const{data:h,error:N}=await q.from("system_templates").update(t).eq("id",l.id).select("id, updated_at").maybeSingle();if(N)throw N;if(!h)throw{code:"PGRST116"};g.success("Template atualizado")}else{const{data:h,error:N}=await q.from("system_templates").insert(t).select("id, updated_at").maybeSingle();if(N)throw N;if(!h)throw{code:"PGRST116"};g.success("Template criado")}z(!1),re()}catch(t){hs.error("Erro ao salvar template:",t),g.error(Us(t,"Erro ao salvar template."))}finally{de.current=!1,ce(!1)}},Ye=async()=>{if(l)try{const{error:a}=await q.from("system_templates").delete().eq("id",l.id);if(a)throw a;g.success("Template excluído"),Y(!1),re()}catch{g.error("Erro ao excluir")}},Qe=async a=>{try{const{error:t}=await q.from("system_templates").update({ativo:!a.ativo}).eq("id",a.id);if(t)throw t;g.success(`Template ${a.ativo?"desativado":"ativado"}`),re()}catch{g.error("Erro ao alterar status")}},he=a=>{const t=a.variaveis;return Array.isArray(t)?t.length:typeof t=="object"&&t!==null?Object.keys(t).length:0};return e.jsx(ms,{children:e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-3",children:[e.jsxs("div",{children:[e.jsx("h1",{className:"text-2xl font-bold text-foreground font-mono",children:"Templates de Laudos"}),e.jsxs("p",{className:"text-muted-foreground text-sm",children:[xe," templates encontrados"]})]}),e.jsxs(x,{onClick:Ue,className:"gap-2",children:[e.jsx(Es,{className:"h-4 w-4"}),"Novo Template"]})]}),e.jsxs("div",{className:"flex flex-wrap gap-4 items-center p-4 bg-muted/30 rounded-lg border border-border",children:[e.jsx("div",{className:"flex-1 min-w-[200px]",children:e.jsxs("div",{className:"relative",children:[e.jsx(Ms,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(A,{placeholder:"Buscar por título, código ou tags...",value:n,onChange:a=>{y(a.target.value),M(1)},className:"pl-10"})]})}),e.jsxs($,{value:_,onValueChange:a=>{E(a),M(1)},children:[e.jsx(B,{className:"w-[160px]",children:e.jsx(J,{placeholder:"Modalidade"})}
7),e.jsxs(H,{children:[e.jsx(p,{value:"all",children:"Todas Modalidades"}),m.map(a=>e.jsx(p,{value:a.codigo,children:a.nome},a.id))]})]}),e.jsxs($,{value:C,onValueChange:a=>{G(a),M(1)},children:[e.jsx(B,{className:"w-[140px]",children:e.jsx(J,{placeholder:"Status"})}),e.jsxs(H,{children:[e.jsx(p,{value:"all",children:"Todos"}),e.jsx(p,{value:"active",children:"Ativos"}),e.jsx(p,{value:"inactive",children:"Inativos"})]})]}),e.jsxs($,{value:K,onValueChange:a=>{oe(a),M(1)},children:[e.jsx(B,{className:"w-[150px]",children:e.jsx(J,{placeholder:"Categoria"})}),e.jsxs(H,{children:[e.jsx(p,{value:"all",children:"Todas Categorias"}),e.jsx(p,{value:"normal",children:"Normal"}),e.jsx(p,{value:"alterado",children:"Alterado"})]})]}),e.jsx(x,{variant:"outline",size:"icon",onClick:()=>re(),disabled:me,children:e.jsx(Rs,{className:`h-4 w-4 ${me?"animate-spin":""}`})})]}),e.jsxs("div",{className:"flex flex-wrap items-center gap-2 -mt-2",children:[e.jsx("span",{className:"text-xs text-muted-foreground mr-1",children:"Recência:"}),[{v:"all",label:"Todos"},{v:"today",label:"Editados hoje"},{v:"week",label:"Esta semana"}].map(a=>e.jsx(x,{size:"sm",variant:U===a.v?"default":"outline",className:"h-7 px-3 text-xs",onClick:()=>{fe(a.v),M(1)},children:a.label},a.v)),e.jsx("span",{className:"mx-2 h-4 w-px bg-border"}),e.jsx("span",{className:"text-xs text-muted-foreground",children:"Ordenar por:"}),e.jsxs(x,{size:"sm",variant:X==="updated"?"default":"outline",className:"h-7 px-3 text-xs gap-1",onClick:()=>ne("updated"),children:[e.jsx(Vs,{className:"h-3 w-3"})," Recentes"]}),e.jsx(x,{size:"sm",variant:X==="modalidade"?"default":"outline",className:"h-7 px-3 text-xs",onClick:()=>ne("modalidade"),children:"Modalidade / Título"})]}),e.jsx("div",{className:"border border-border rounded-lg overflow-x-auto",children:e.jsxs(gs,{className:"min-w-[900px]",children:[e.jsx(js,{children:e.jsxs(_e,{className:"bg-muted/50",children:[e.jsx(L,{className:"w-[100px]",children:"Código"}),e.jsx(L,{children:"Título"}),e.jsx(L,{className:"w-[100px]",children:"Modalidade"}),e.jsx(L,{className:"w-[90px]",children:"Atalho"}),e.jsx(L,{className:"w-[100px]",children:"Categoria"}),e.jsx(L,{className:"w-[80px] text-center",children:"Vars"}),e.jsx(L,{className:"w-[120px]",children:"Atualizado"}),e.jsx(L,{className:"w-[80px] text-center",children:"Status"}),e.jsx(L,{className:"w-[160px] text-right",children:"Ações"})]})}),e.jsx(fs,{children:Ee.length===0?e.jsx(_e,{children:e.jsx(P,{colSpan:9,className:"text-center py-8 text-muted-foreground",children:me?"Carregando...":"Nenhum template encontrado"})}):Ee.map(a=>e.jsxs(_e,{className:"hover:bg-muted/30 relative",children:[e.jsxs(P,{className:"font-mono text-xs relative",children:[e.jsx(zs,{date:a.updated_at}),a.codigo]}),e.jsxs(P,{children:[e.jsx("div",{className:"font-medium text-sm",children:a.titulo}),a.tags&&a.tags.length>0&&e.jsxs("div",{className:"flex gap-1 mt-1",children:[a.tags.slice(0,3).map((t,h)=>e.jsx(R,{variant:"secondary",className:"text-[10px] px-1 py-0",children:t},h)),a.tags.length>3&&e.jsxs("span",{className:"text-[10px] text-muted-foreground",children:["+",a.tags.length-3]})]})]}),e.jsx(P,{children:e.jsx(R,{variant:"outline",children:a.modalidade_codigo})}),e.jsx(P,{children:a.atalho&&e.jsx(R,{variant:"secondary",className:"font-mono text-xs bg-primary/10 text-primary",children:a.atalho})}),e.jsx(P,{children:e.jsx(R,{variant:a.categoria==="normal"?"secondary":"destructive",className:a.categoria==="normal"?"bg-emerald-500/20 text-emerald-700 border-emerald-500/30":"",children:a.categoria==="normal"?"Normal":"Alterado"})}),e.jsx(P,{className:"text-center tabular-nums",children:he(a)>0?e.jsxs(R,{variant:"secondary",className:"gap-1",children:[e.jsx(Os,{className:"h-3 w-3"}),he(a)]}):e.jsx("span",{className:"text-muted-foreground text-xs",children:"-"})}),e.jsx(P,{children:e.jsx(Ds,{date:a.updated_at,compact:!0})}),e.jsx(P,{className:"text-center",children:e.jsx(te,{checked:a.ativo,onCheckedChange:()=>Qe(a),className:"scale-75"})}),e.jsx(P,{className:"text-right",children:e.jsxs("div",{className:"flex justify-end gap-1",children:[e.jsx(x,{variant:"ghost",size:"icon",onClick:()=>{Xe(a)},disabled:Q===a.id,title:"Visualizar",children:Q===a.id?e.jsx(De,{className:"h-4 w-4 animate-spin"}):e.jsx(Se,{className:"h-4 w-4"})}),e.jsx(x,{variant:"ghost",size:"icon",onClick:()=>{Me(a)},disabled:Q===a.id,title:"Editar",children:e.jsx($e,{className:"h-4 w-4"})}),e.jsx(x,{variant:"ghost",size:"icon",onClick:()=>{Ke(a)},disabled:Q===a.id,title:"Duplicar",children:e.jsx(ks,{className:"h-4 w-4"})}),e.jsx(x,{variant:"ghost",size:"icon",onClick:()=>Ge(a),title:"Excluir",className:"text-destructive hover:text-destructive",children:e.jsx(Ae,{className:"h-4 w-4"})})]})})]},a.id))})]})}),ue>1&&e.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-3",children:[e.jsxs("span",{className:"text-sm text-muted-foreground tabular-nums",children:["Mostrando ",(b-1)*le+1," - ",Math.min(b*le,xe)," de ",xe]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(x,{variant:"outline",size:"sm",onClick:()=>M(a=>Math.max(1,a-1)),disabled:b===1,children:e.jsx(Fs,{className:"h-4 w-4"})}),e.jsxs("span",{className:"flex items-center px-3 text-sm",children:[b," / ",ue]}),e.jsx(x,{variant:"outline",size:"sm",onClick:()=>M(a=>Math.min(ue,a+1)),disabled:b===ue,children:e.jsx(Ps,{className:"h-4 w-4"})})]})]}),e.jsx(Ne,{open:w,onOpenChange:a=>!O&&z(a),children:e.jsxs(be,{className:"max-w-4xl max-h-[90vh] overflow-hidden flex flex-col",children:[e.jsx(ye,{children:e.jsxs(Ce,{className:"flex items-center gap-2",children:[e.jsx(Je,{className:"h-5 w-5"}),l?"Editar Template":"Novo Template"]})}),l&&e.jsx($s,{createdAt:l.created_at,updatedAt:l.updated_at,version:l.version}),e.jsxs(xs,{value:k,onValueChange:c,className:"flex-1 overflow-hidden flex flex-col",children:[e.jsxs(us,{className:`flex w-full overflow-x-auto sm:grid ${l?"sm:grid-cols-6":"sm:grid-cols-5"}`,children:[e.jsx(ee,{value:"basico",children:"Básico"}),e.jsx(ee,{value:"conteudo",children:"Conteúdo"}),e.jsx(ee,{value:"variaveis",children:"Variáveis"}),e.jsx(ee,{value:"config",children:"Configurações"}),e.jsxs(ee,{value:"preview",className:"gap-1.5",children:[e.jsx(He,{className:"h-3.5 w-3.5"}),"Preview"]}),l&&e.jsxs(ee,{value:"historico",className:"gap-1.5",children:[e.jsx(Is,{className:"h-3.5 w-3.5"}),"Histórico"]})]}),e.jsxs("div",{className:"flex-1 overflow-y-auto mt-4",children:[e.jsxs(se,{value:"basico",className:"space-y-4 m-0",children:[e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(i,{htmlFor:"codigo",children:"Código *"}),e.jsx(A,{id:"codigo",value:s.codigo||"",onChange:a=>o({...s,codigo:a.target.value.toUpperCase()}),placeholder:"TC_TORAX_NORMAL_001",className:"font-mono"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Formato: MODALIDADE_REGIAO_TIPO_NUMERO. Ex: TC_TORAX_NORMAL_001, RM_CRANIO_AVC_002, US_ABD_COLECISTITE_001"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(i,{htmlFor:"titulo",children:"Título *"}),e.jsx(A,{id:"titulo",value:s.titulo||"",onChange:a=>o({...s,titulo:a.target.value}),placeholder:"TC de Tórax Normal"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:'Título descritivo para busca. Ex: "TC de Tórax Normal", "RM de Crânio - Sequelas de AVC"'})]})]}),e.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-2 md:grid-cols-3 gap-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(i,{children:"Categoria *"}),e.jsxs($,{value:s.categoria||"normal",onValueChange:a=>o({...s,categoria:a}),children:[e.jsx(B,{children:e.jsx(J,{placeholder:"Selecione..."})}
7),e.jsxs(H,{children:[e.jsx(p,{value:"normal",children:"Normal - Estudo sem alterações"}),e.jsx(p,{value:"alterado",children:"Alterado - Achados patológicos"})]})]}),e.jsx("p",{className:"text-xs text-muted-foreground",children:'Templates "alterados" incluem patologias, achados positivos ou pós-operatórios.'})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(i,{children:"Modalidade *"}),e.jsxs($,{value:s.modalidade_codigo||"",onValueChange:a=>o({...s,modalidade_codigo:a}),children:[e.jsx(B,{children:e.jsx(J,{placeholder:"Selecione..."})}),e.jsx(H,{children:m.map(a=>e.jsxs(p,{value:a.codigo,children:[a.nome," (",a.codigo,")"]},a.id))})]}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"TC=Tomografia, RM=Ressonância, US=Ultrassom, RX=Radiografia, MG=Mamografia"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(i,{children:"Região Anatômica"}),e.jsxs($,{value:s.regiao_codigo||"",onValueChange:a=>o({...s,regiao_codigo:a}),children:[e.jsx(B,{children:e.jsx(J,{placeholder:"Selecione..."})}),e.jsx(H,{children:v.map(a=>e.jsx(p,{value:a.codigo,children:a.nome},a.id))})]}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Região anatômica principal do exame. Deixe vazio se aplicável a múltiplas regiões."})]})]}),e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(i,{htmlFor:"atalho",children:"Atalho Rápido"}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"text-muted-foreground font-mono text-lg",children:";"}),e.jsx(A,{id:"atalho",value:s.atalho||"",onChange:a=>o({...s,atalho:a.target.value.toLowerCase().replace(/[^a-z0-9]/g,"").slice(0,15)}),placeholder:"tctnor",className:"font-mono",maxLength:15})]}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:["Digite ",e.jsx("code",{className:"bg-muted px-1 rounded",children:s.atalho||"atalho"})," no editor e prima ",e.jsx("strong",{children:"Espaço"})," ou ",e.jsx("strong",{children:"Enter"})," para inserir este template automaticamente. 2-15 caracteres, apenas letras e números."]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(i,{htmlFor:"tags",children:"Tags (separadas por vírgula)"}),e.jsx(A,{id:"tags",value:((Re=s.tags)==null?void 0:Re.join(", "))||"",onChange:a=>o({...s,tags:a.target.value.split(",").map(t=>t.trim()).filter(Boolean)}),placeholder:"normal, protocolo, tórax"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Palavras-chave para busca rápida. Ex: normal, urgência, pediátrico, contraste"})]})]})]}),e.jsxs(se,{value:"conteudo",className:"space-y-4 m-0",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(i,{children:"Técnica (JSON)"}),e.jsx(ae,{value:JSON.stringify(s.tecnica||{},null,2),onChange:a=>{try{const t=JSON.parse(a.target.value);o({...s,tecnica:t})}catch{}},className:"font-mono text-sm min-h-[100px]",placeholder:'{"SEM": "Texto sem contraste", "EV": "Texto com contraste"}'}),e.jsxs("details",{className:"text-xs text-muted-foreground",children:[e.jsx("summary",{className:"cursor-pointer hover:text-foreground",children:"Dica: Chaves: SEM, EV, VO, PRIMOVIST"}),e.jsxs("div",{className:"mt-1 pl-3 border-l-2 border-muted",children:["Ex: ",'{"SEM": "Realizado estudo sem contraste", "EV": "Estudo após contraste iodado EV"}']})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(i,{htmlFor:"achados",children:"Achados *"}),e.jsx(ae,{id:"achados",value:s.achados||"",onChange:a=>o({...s,achados:a.target.value}),className:"min-h-[150px]",placeholder:"Descreva os achados do exame. Use {{variavel}} para variáveis dinâmicas."}),e.jsxs("details",{className:"text-xs text-muted-foreground",children:[e.jsxs("summary",{className:"cursor-pointer hover:text-foreground",children:["Dica: Use ","{{variavel}}"," para campos dinâmicos"]}),e.jsxs("div",{className:"mt-1 pl-3 border-l-2 border-muted",children:['Ex: "Fígado medindo ',"{{medida_x}}"," x ","{{medida_y}}"," cm, com ecotextura ","{{ecotextura}}",'."']})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(i,{htmlFor:"impressao",children:"Impressão *"}),e.jsx(ae,{id:"impressao",value:s.impressao||"",onChange:a=>o({...s,impressao:a.target.value}),className:"min-h-[80px]",placeholder:"Conclusão/impressão diagnóstica"}),e.jsxs("details",{className:"text-xs text-muted-foreground",children:[e.jsx("summary",{className:"cursor-pointer hover:text-foreground",children:'Dica: Conclusão em formato lista com "-"'}),e.jsxs("div",{className:"mt-1 pl-3 border-l-2 border-muted",children:['Evite medidas exatas. Ex: "- Sinais de esteatose hepática grau ',"{{grau}}",'."']}
7)]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(i,{htmlFor:"adicionais",children:"Informações Adicionais"}),e.jsx(ae,{id:"adicionais",value:s.adicionais||"",onChange:a=>o({...s,adicionais:a.target.value}),className:"min-h-[60px]",placeholder:"Observações, recomendações (opcional)"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:'Opcional. Ex: "Correlacionar clinicamente."'})]})]}),e.jsxs(se,{value:"variaveis",className:"space-y-4 m-0",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(i,{children:"Variáveis (JSON Array)"}),e.jsx(ae,{value:JSON.stringify(s.variaveis||[],null,2),onChange:a=>{try{const t=JSON.parse(a.target.value);o({...s,variaveis:t})}catch{}},className:"font-mono text-sm min-h-[250px]",placeholder:`[
8  {
9    "nome": "medida_x",
10    "tipo": "numero",
11    "descricao": "Medida em X",
12    "unidade": "cm",
13    "obrigatorio": true
14  },
15  {
16    "nome": "lado",
17    "tipo": "select",
18    "opcoes": ["direito", "esquerdo", "bilateral"]
19  }
20]`}),e.jsxs("div",{className:"text-xs text-muted-foreground mt-2 space-y-1 bg-muted/50 p-3 rounded-md",children:[e.jsx("p",{className:"font-medium",children:"Tipos disponíveis: texto, numero, select, boolean"}),e.jsx("p",{children:"Campos: nome (snake_case), tipo, descricao, obrigatorio, valor_padrao, unidade, opcoes"}),e.jsxs("p",{children:["Use ","{{nome_variavel}}"," no conteúdo (achados/impressão) para referenciar a variável."]}),e.jsxs("details",{className:"cursor-pointer mt-2",children:[e.jsx("summary",{className:"text-primary hover:underline font-medium",children:"Ver exemplo completo"}),e.jsx("pre",{className:"mt-2 text-[11px] overflow-x-auto bg-background p-2 rounded border",children:`[
21  {"nome": "medida_x", "tipo": "numero", "unidade": "cm", "obrigatorio": true},
22  {"nome": "lado", "tipo": "select", "opcoes": ["direito", "esquerdo", "bilateral"]},
23  {"nome": "ecotextura", "tipo": "select", "opcoes": ["homogênea", "heterogênea"], "valor_padrao": "homogênea"},
24  {"nome": "contraste", "tipo": "boolean", "valor_padrao": false}
25]`})]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(i,{children:"Condições Lógicas (JSON Array)"}),e.jsx(ae,{value:JSON.stringify(s.condicoes_logicas||[],null,2),onChange:a=>{try{const t=JSON.parse(a.target.value);o({...s,condicoes_logicas:t})}catch{}},className:"font-mono text-sm min-h-[100px]",placeholder:`[
26  {
27    "quando": "lado",
28    "igual": "bilateral",
29    "derivar": { "prefixo": "Bilateralmente" }
30  }
31]`}),e.jsxs("details",{className:"text-xs text-muted-foreground",children:[e.jsx("summary",{className:"cursor-pointer hover:text-foreground",children:"Dica: Regras para derivar valores automaticamente"}),e.jsx("div",{className:"mt-1 pl-3 border-l-2 border-muted",children:'Ex: quando lado="bilateral" → adicionar prefixo "Bilateralmente" ao texto.'})]})]})]}),e.jsxs(se,{value:"config",className:"space-y-4 m-0",children:[e.jsxs("div",{className:"flex items-center justify-between p-4 bg-muted/30 rounded-lg",children:[e.jsxs("div",{children:[e.jsx(i,{className:"text-base",children:"Template Ativo"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Templates inativos não aparecem para seleção"})]}),e.jsx(te,{checked:s.ativo??!0,onCheckedChange:a=>o({...s,ativo:a})})]}),e.jsxs("div",{className:"p-4 bg-muted/30 rounded-lg space-y-4",children:[e.jsxs("div",{children:[e.jsx(i,{className:"text-base font-semibold",children:"Configuração de Técnica"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Define como as opções de técnica são apresentadas no modal de variáveis"})]}),e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(i,{children:"Tipo de Apresentação"}),e.jsxs($,{value:r.tipo,onValueChange:a=>f({...r,tipo:a}),children:[e.jsx(B,{children:e.jsx(J,{})}
31),e.jsxs(H,{children:[e.jsx(p,{value:"auto",children:"🔄 Auto (detectar)"}),e.jsx(p,{value:"alternativo",children:"☑️ Alternativo (checkboxes)"}),e.jsx(p,{value:"complementar",children:"Complementar (todos concatenados)"}),e.jsx(p,{value:"unico",children:"1️⃣ Único (sem seleção)"}),e.jsx(p,{value:"misto",children:"🔀 Misto (info + opções)"})]})]}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Alternativo: usuário escolhe uma opção. Complementar: todas as partes são concatenadas."})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(i,{children:"Separador"}),e.jsx(A,{value:r.separador??". ",onChange:a=>f({...r,separador:a.target.value}),placeholder:". ",className:"font-mono"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:'Texto usado entre partes concatenadas. Ex: ". " ou " | "'})]}),e.jsxs("div",{className:"flex items-center gap-3 p-3 bg-background rounded-md border",children:[e.jsx(te,{checked:r.concatenar,onCheckedChange:a=>f({...r,concatenar:a})}),e.jsxs("div",{children:[e.jsx(i,{className:"cursor-pointer",children:"Concatenar seleções"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Une múltiplas técnicas selecionadas"})]})]}),e.jsxs("div",{className:"flex items-center gap-3 p-3 bg-background rounded-md border",children:[e.jsx(te,{checked:r.prefixo_label??!1,onCheckedChange:a=>f({...r,prefixo_label:a})}),e.jsxs("div",{children:[e.jsx(i,{className:"cursor-pointer",children:"Mostrar prefixo"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:'Ex: "Posição: ortostática"'})]})]})]}),r.tipo!=="auto"&&e.jsxs("div",{className:"flex gap-2 pt-2 border-t border-border/50",children:[e.jsx(R,{variant:"outline",className:"text-xs",children:r.tipo}),r.concatenar&&e.jsx(R,{variant:"secondary",className:"text-xs",children:"Concatena"}),r.prefixo_label&&e.jsx(R,{variant:"secondary",className:"text-xs",children:"Com prefixo"}),r.separador&&r.separador!==". "&&e.jsxs(R,{variant:"secondary",className:"text-xs font-mono",children:['sep: "',r.separador,'"']})]})]}),l&&e.jsxs("div",{className:"p-4 bg-muted/30 rounded-lg space-y-2",children:[e.jsx(i,{className:"text-base",children:"Informações do Sistema"}),e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-4 text-sm",children:[e.jsxs("div",{children:[e.jsx("span",{className:"text-muted-foreground",children:"ID:"}),e.jsx("span",{className:"ml-2 font-mono text-xs",children:l.id})]}),e.jsxs("div",{children:[e.jsx("span",{className:"text-muted-foreground",children:"Versão:"}),e.jsx("span",{className:"ml-2",children:l.version||1})]}),e.jsxs("div",{children:[e.jsx("span",{className:"text-muted-foreground",children:"Criado:"}),e.jsx("span",{className:"ml-2",children:l.created_at?new Date(l.created_at).toLocaleString("pt-BR"):"-"})]}),e.jsxs("div",{children:[e.jsx("span",{className:"text-muted-foreground",children:"Atualizado:"}),e.jsx("span",{className:"ml-2",children:l.updated_at?new Date(l.updated_at).toLocaleString("pt-BR"):"-"})]})]})]})]}),e.jsx(se,{value:"preview",className:"m-0",children:e.jsx(Js,{formData:s,tecnicaConfigForm:r})}),l&&e.jsx(se,{value:"historico",className:"m-0",children:e.jsx(Bs,{sourceTable:"system_templates",sourceId:l.id,onRestore:a=>{o(t=>({...t,titulo:a.titulo??t.titulo,achados:a.achados??t.achados,impressao:a.impressao??t.impressao,adicionais:a.adicionais??t.adicionais,conteudo_template:a.conteudo_template??t.conteudo_template,indicacao_clinica:a.indicacao_clinica??t.indicacao_clinica,variaveis:a.variaveis??t.variaveis,categoria:a.categoria??t.categoria})),c("basico")}})})]})]}),e.jsxs(we,{className:"mt-4",children:[e.jsx(x,{variant:"outline",onClick:()=>z(!1),disabled:O,children:"Cancelar"}),e.jsxs(x,{onClick:We,className:"gap-2",disabled:O,children:[O?e.jsx(De,{className:"h-4 w-4 animate-spin"}):e.jsx(qs,{className:"h-4 w-4"}),l?"Salvar Alterações":"Criar Template"]})]})]})}),e.jsx(Ne,{open:S,onOpenChange:j,children:e.jsxs(be,{className:"max-w-3xl max-h-[90vh] overflow-y-auto",children:[e.jsx(ye,{children:e.jsxs(Ce,{className:"flex items-center gap-2",children:[e.jsx(Se,{className:"h-5 w-5"}),"Visualizar Template"]})}),l&&e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-4",children:[e.jsxs("div",{children:[e.jsx(i,{className:"text-muted-foreground",children:"Código"}),e.jsx("p",{className:"font-mono",children:l.codigo})]}),e.jsxs("div",{children:[e.jsx(i,{className:"text-muted-foreground",children:"Título"}),e.jsx("p",{children:l.titulo})]}),e.jsxs("div",{children:[e.jsx(i,{className:"text-muted-foreground",children:"Modalidade"}),e.jsx(R,{children:l.modalidade_codigo})]}),e.jsxs("div",{children:[e.jsx(i,{className:"text-muted-foreground",children:"Região"}),e.jsx("p",{children:l.regiao_codigo||"-"})]})]}),e.jsxs("div",{children:[e.jsx(i,{className:"text-muted-foreground",children:"Tags"}),e.jsx("div",{className:"flex flex-wrap gap-1 mt-1",children:((Ve=l.tags)==null?void 0:Ve.map((a,t)=>e.jsx(R,{variant:"secondary",children:a},t)))||e.jsx("span",{className:"text-muted-foreground",children:"-"})})]}),e.jsxs("div",{children:[e.jsx(i,{className:"text-muted-foreground",children:"Técnica"}),e.jsx("pre",{className:"text-xs bg-muted p-2 rounded mt-1 overflow-x-auto",children:JSON.stringify(l.tecnica,null,2)})]}),e.jsxs("div",{children:[e.jsx(i,{className:"text-muted-foreground",children:"Achados"}),e.jsx("div",{className:"text-sm bg-muted p-2 rounded mt-1 whitespace-pre-wrap",children:l.achados||"-"})]}),e.jsxs("div",{children:[e.jsx(i,{className:"text-muted-foreground",children:"Impressão"}),e.jsx("div",{className:"text-sm bg-muted p-2 rounded mt-1 whitespace-pre-wrap",children:l.impressao||"-"})]}),he(l)>0&&e.jsxs("div",{children:[e.jsxs(i,{className:"text-muted-foreground",children:["Variáveis (",he(l),")"]}),e.jsx("pre",{className:"text-xs bg-muted p-2 rounded mt-1 overflow-x-auto",children:JSON.stringify(l.variaveis,null,2)})]})]}),e.jsxs(we,{children:[e.jsx(x,{variant:"outline",onClick:()=>j(!1),children:"Fechar"}),e.jsxs(x,{onClick:()=>{j(!1),Me(l)},children:[e.jsx($e,{className:"h-4 w-4 mr-2"}),"Editar"]})]})]})}),e.jsx(Ne,{open:W,onOpenChange:Y,children:e.jsxs(be,{children:[e.jsx(ye,{children:e.jsxs(Ce,{className:"text-destructive flex items-center gap-2",children:[e.jsx(Ae,{className:"h-5 w-5"}),"Confirmar Exclusão"]})}),e.jsxs("p",{className:"text-muted-foreground",children:["Tem certeza que deseja excluir o template ",e.jsx("strong",{children:l==null?void 0:l.titulo}),"? Esta ação não pode ser desfeita."]}),e.jsxs(we,{children:[e.jsx(x,{variant:"outline",onClick:()=>Y(!1),children:"Cancelar"}),e.jsx(x,{variant:"destructive",onClick:Ye,children:"Excluir"})]})]})})]})})}export{la 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.