var __gh = require("react").createElement, __gf = require("react").Fragment; var __defProp=Object.defineProperty;var __getOwnPropDesc=Object.getOwnPropertyDescriptor;var __getOwnPropNames=Object.getOwnPropertyNames;var __hasOwnProp=Object.prototype.hasOwnProperty;var __export=(target,all)=>{for(var name in all)__defProp(target,name,{get:all[name],enumerable:!0})},__copyProps=(to,from,except,desc)=>{if(from&&typeof from=="object"||typeof from=="function")for(let key of __getOwnPropNames(from))!__hasOwnProp.call(to,key)&&key!==except&&__defProp(to,key,{get:()=>from[key],enumerable:!(desc=__getOwnPropDesc(from,key))||desc.enumerable});return to};var __toCommonJS=mod=>__copyProps(__defProp({},"__esModule",{value:!0}),mod);var stdin_exports={};__export(stdin_exports,{default:()=>stdin_default,featureConfig:()=>featureConfig});module.exports=__toCommonJS(stdin_exports);var dataSources=[{key:"documentos",table:"alquiler__documentos_firma",access:[]}];var featureConfig={dataSources,seedData:[],meta:{name:"Firma de documentos (p\xFAblico)",version:"2.0.0"}};var import_react2=require("react");var import_react=require("react"),import_lucide_react=require("lucide-react"),ACCENT="#1d1d1f";function LogoMarca({marca,tam}){let r=Math.round(tam*.26);return marca.logo?__gh("img",{src:"/api/files/serve?path="+encodeURIComponent(marca.logo),alt:marca.nombre,style:{width:tam,height:tam,borderRadius:r,objectFit:"cover",display:"block"},"data-gufi-src":"components/DocumentoFirma.tsx:39"}):__gh("span",{style:{width:tam,height:tam,borderRadius:r,background:ACCENT,color:"#fff",fontSize:Math.round(tam*.46),fontWeight:650,display:"flex",alignItems:"center",justifyContent:"center"},"data-gufi-src":"components/DocumentoFirma.tsx:40"},marca.nombre.slice(0,1).toUpperCase())}var MOTIVOS={enlace:"Este enlace no es v\xE1lido o el documento se ha anulado. Pide a la agencia que te lo env\xEDe de nuevo.",demasiados_intentos:"Demasiados intentos desde esta conexi\xF3n. Espera unos minutos y vuelve a abrir el enlace.",ya_firmado:"Este documento ya est\xE1 firmado.",falta_aceptar:"Marca la casilla para confirmar que has le\xEDdo el documento.",pdf:"No se ha podido generar el documento firmado. No se ha guardado nada: vuelve a pulsar \xABFirmar\xBB."},ETIQUETA_ERROR={nombre:"Escribe tu nombre y apellidos.",dni:"El DNI o NIE no es v\xE1lido. Revisa la letra.",email:"El correo no es v\xE1lido.",telefono:"El tel\xE9fono no es v\xE1lido.",contacto:"Deja al menos un tel\xE9fono o un correo.",firma:"Falta tu firma."};function DocumentoFirma({token,llamar:llamar2,marca}){let[vista,setVista]=(0,import_react.useState)(null),[aviso,setAviso]=(0,import_react.useState)(null),[errores,setErrores]=(0,import_react.useState)([]),[firmante,setFirmante]=(0,import_react.useState)({nombre:"",dni:"",email:"",telefono:""}),[valores,setValores]=(0,import_react.useState)({}),[acepto,setAcepto]=(0,import_react.useState)(!1),[hayFirma,setHayFirma]=(0,import_react.useState)(!1),[enviando,setEnviando]=(0,import_react.useState)(!1),[hecho,setHecho]=(0,import_react.useState)(null),[altoDoc,setAltoDoc]=(0,import_react.useState)(420),lienzo=(0,import_react.useRef)(null),dibujando=(0,import_react.useRef)(!1),ultimo=(0,import_react.useRef)(null);(0,import_react.useEffect)(()=>{llamar2("documento_firma",{t:token,accion:"ver"}).then(r=>{if(!r.ok){setAviso(MOTIVOS[r.motivo||"enlace"]||MOTIVOS.enlace);return}setVista(r),r.firmante&&setFirmante(r.firmante),r.campos&&setValores(Object.fromEntries(r.campos.map(c=>[c.key,c.valor||""])))}).catch(e=>setAviso(e?.message||MOTIVOS.enlace))},[token,llamar2]);let prepararLienzo=(0,import_react.useCallback)(()=>{let c=lienzo.current;if(!c)return;let r=c.getBoundingClientRect();if(!r.width)return;let k=Math.max(window.devicePixelRatio||1,1);c.width=r.width*k,c.height=r.height*k;let ctx=c.getContext("2d");ctx&&(ctx.scale(k,k),ctx.lineWidth=2.2,ctx.lineCap="round",ctx.lineJoin="round",ctx.strokeStyle="#16150f")},[]);(0,import_react.useEffect)(()=>{if(!(!vista||vista.firmado))return prepararLienzo(),window.addEventListener("resize",prepararLienzo),()=>window.removeEventListener("resize",prepararLienzo)},[vista,prepararLienzo]);let punto=e=>{let r=e.target.getBoundingClientRect();return{x:e.clientX-r.left,y:e.clientY-r.top}},empezar=e=>{e.target.setPointerCapture(e.pointerId),dibujando.current=!0,ultimo.current=punto(e)},mover=e=>{if(!dibujando.current)return;let ctx=lienzo.current?.getContext("2d"),p=punto(e);!ctx||!ultimo.current||(ctx.beginPath(),ctx.moveTo(ultimo.current.x,ultimo.current.y),ctx.lineTo(p.x,p.y),ctx.stroke(),ultimo.current=p,hayFirma||setHayFirma(!0))},soltar=()=>{dibujando.current=!1,ultimo.current=null},borrar=()=>{let c=lienzo.current,ctx=c?.getContext("2d");c&&ctx&&ctx.clearRect(0,0,c.width,c.height),setHayFirma(!1)},firmar=async()=>{if(vista){if(setErrores([]),setAviso(null),!hayFirma||!lienzo.current){setErrores(["firma"]);return}if(!acepto){setAviso(MOTIVOS.falta_aceptar);return}setEnviando(!0);try{let r=await llamar2("documento_firma",{t:token,accion:"firmar",firmante,campos:valores,acepto:!0,firma:lienzo.current.toDataURL("image/png"),user_agent:navigator.userAgent});if(r.ok){setHecho({pdf:r.pdf,nombre:r.pdf_nombre});return}if(r.motivo==="datos"){setErrores(r.errores||[]);return}setAviso(MOTIVOS[r.motivo]||"No se ha podido firmar.")}catch(e){setAviso(e?.message||"No se ha podido firmar.")}finally{setEnviando(!1)}}},descargar=(dataUrl,nombre)=>{let a=document.createElement("a");a.href=dataUrl,a.download=nombre,document.body.appendChild(a),a.click(),a.remove()},marco=hijos=>__gh("div",{className:"min-h-screen bg-[#faf9f6] px-4 py-6 sm:py-10",style:{fontFamily:'-apple-system, "SF Pro Text", "Segoe UI", sans-serif',color:"#16150f"},"data-gufi-src":"components/DocumentoFirma.tsx:172"},__gh("div",{className:"max-w-[720px] mx-auto","data-gufi-src":"components/DocumentoFirma.tsx:173"},hijos));if(aviso&&!vista)return marco(__gh("p",{className:"text-[15px] text-[#54524a] text-center mt-16","data-gufi-src":"components/DocumentoFirma.tsx:177"},aviso));if(!vista)return marco(__gh("div",{className:"flex justify-center mt-24","data-gufi-src":"components/DocumentoFirma.tsx:178"},__gh(import_lucide_react.Loader2,{className:"w-7 h-7 animate-spin",style:{color:ACCENT}})));let cabecera=__gh("div",{className:"mb-5 flex items-center gap-3","data-gufi-src":"components/DocumentoFirma.tsx:181"},__gh(LogoMarca,{marca,tam:40}),__gh("div",{"data-gufi-src":"components/DocumentoFirma.tsx:183"},__gh("div",{className:"text-[13px] text-[#8d8a7f]","data-gufi-src":"components/DocumentoFirma.tsx:184"},vista.empresa),__gh("h1",{className:"text-[24px] font-semibold tracking-[-0.01em] mt-0.5","data-gufi-src":"components/DocumentoFirma.tsx:185"},vista.tipo)));if(hecho||vista.firmado){let pdf=hecho?hecho.pdf:vista.pdf,nombre=hecho?hecho.nombre:vista.pdf_nombre;return marco(__gh(__gf,null,cabecera,__gh("div",{className:"bg-white border border-[#e4e0d7] rounded-2xl p-6 text-center","data-gufi-src":"components/DocumentoFirma.tsx:196"},__gh(import_lucide_react.CheckCircle2,{className:"w-10 h-10 mx-auto",style:{color:ACCENT}}),__gh("div",{className:"text-[18px] font-semibold mt-3","data-gufi-src":"components/DocumentoFirma.tsx:198"},"Documento firmado"),__gh("p",{className:"text-[14px] text-[#54524a] mt-1.5","data-gufi-src":"components/DocumentoFirma.tsx:199"},"Guarda tu copia. La agencia ya tiene la suya."),pdf&&nombre&&__gh("button",{type:"button",onClick:()=>descargar(pdf,nombre),className:"mt-5 inline-flex items-center gap-2 h-11 px-5 rounded-xl text-white text-[15px] font-medium",style:{background:ACCENT},"data-gufi-src":"components/DocumentoFirma.tsx:201"},__gh(import_lucide_react.Download,{className:"w-4 h-4"})," Descargar el PDF"))))}let pendientes=(vista.campos||[]).filter(c=>!c.valor),err=k=>errores.includes(k),entrada="w-full h-11 px-3 rounded-xl border bg-white text-[15px] outline-none focus:border-[#1d4a3e]",borde=k=>err(k)?"border-[#b42318]":"border-[#e4e0d7]";return marco(__gh(__gf,null,cabecera,__gh("div",{className:"bg-white border border-[#e4e0d7] rounded-2xl overflow-hidden","data-gufi-src":"components/DocumentoFirma.tsx:224"},__gh("iframe",{title:vista.titulo,srcDoc:vista.html,sandbox:"allow-same-origin",className:"w-full block border-0",style:{height:altoDoc},onLoad:e=>{let d=e.target.contentDocument;d&&setAltoDoc(Math.min(d.documentElement.scrollHeight+4,2400))},"data-gufi-src":"components/DocumentoFirma.tsx:225"})),__gh("div",{className:"bg-white border border-[#e4e0d7] rounded-2xl p-5 mt-4 space-y-3.5","data-gufi-src":"components/DocumentoFirma.tsx:238"},__gh("div",{className:"text-[13px] text-[#8d8a7f]","data-gufi-src":"components/DocumentoFirma.tsx:239"},"Tus datos"),__gh("label",{className:"block","data-gufi-src":"components/DocumentoFirma.tsx:240"},__gh("span",{className:"text-[13px] text-[#54524a]","data-gufi-src":"components/DocumentoFirma.tsx:241"},"Nombre y apellidos"),__gh("input",{className:`${entrada} ${borde("nombre")} mt-1`,value:firmante.nombre,autoComplete:"name",onChange:e=>setFirmante({...firmante,nombre:e.target.value}),"data-gufi-src":"components/DocumentoFirma.tsx:242"})),__gh("label",{className:"block","data-gufi-src":"components/DocumentoFirma.tsx:245"},__gh("span",{className:"text-[13px] text-[#54524a]","data-gufi-src":"components/DocumentoFirma.tsx:246"},"DNI o NIE"),__gh("input",{className:`${entrada} ${borde("dni")} mt-1 uppercase`,value:firmante.dni,onChange:e=>setFirmante({...firmante,dni:e.target.value}),"data-gufi-src":"components/DocumentoFirma.tsx:247"})),__gh("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-3.5","data-gufi-src":"components/DocumentoFirma.tsx:250"},__gh("label",{className:"block","data-gufi-src":"components/DocumentoFirma.tsx:251"},__gh("span",{className:"text-[13px] text-[#54524a]","data-gufi-src":"components/DocumentoFirma.tsx:252"},"Tel\xE9fono"),__gh("input",{className:`${entrada} ${borde("telefono")} ${err("contacto")?"border-[#b42318]":""} mt-1`,value:firmante.telefono,inputMode:"tel",autoComplete:"tel",onChange:e=>setFirmante({...firmante,telefono:e.target.value}),"data-gufi-src":"components/DocumentoFirma.tsx:253"})),__gh("label",{className:"block","data-gufi-src":"components/DocumentoFirma.tsx:256"},__gh("span",{className:"text-[13px] text-[#54524a]","data-gufi-src":"components/DocumentoFirma.tsx:257"},"Correo"),__gh("input",{className:`${entrada} ${borde("email")} ${err("contacto")?"border-[#b42318]":""} mt-1`,value:firmante.email,inputMode:"email",autoComplete:"email",onChange:e=>setFirmante({...firmante,email:e.target.value}),"data-gufi-src":"components/DocumentoFirma.tsx:258"}))),pendientes.map(c=>__gh("label",{key:c.key,className:"block","data-gufi-src":"components/DocumentoFirma.tsx:264"},__gh("span",{className:"text-[13px] text-[#54524a]","data-gufi-src":"components/DocumentoFirma.tsx:265"},c.label),c.tipo==="parrafo"?__gh("textarea",{className:`w-full min-h-[96px] px-3 py-2.5 rounded-xl border bg-white text-[15px] outline-none focus:border-[#1d4a3e] ${borde("campo:"+c.key)} mt-1`,value:valores[c.key]||"",onChange:e=>setValores({...valores,[c.key]:e.target.value}),"data-gufi-src":"components/DocumentoFirma.tsx:267"}):__gh("input",{className:`${entrada} ${borde("campo:"+c.key)} mt-1`,type:c.tipo==="fecha"?"date":"text",inputMode:c.tipo==="numero"||c.tipo==="moneda"?"decimal":void 0,value:valores[c.key]||"",onChange:e=>setValores({...valores,[c.key]:e.target.value}),"data-gufi-src":"components/DocumentoFirma.tsx:270"}))),errores.length>0&&__gh("div",{className:"text-[13.5px] text-[#b42318] space-y-0.5","data-gufi-src":"components/DocumentoFirma.tsx:279"},errores.map(k=>__gh("div",{key:k,"data-gufi-src":"components/DocumentoFirma.tsx:280"},ETIQUETA_ERROR[k]||"Revisa: "+((vista.campos||[]).find(c=>"campo:"+c.key===k)?.label||k))))),__gh("div",{className:"bg-white border border-[#e4e0d7] rounded-2xl p-5 mt-4","data-gufi-src":"components/DocumentoFirma.tsx:285"},__gh("div",{className:"flex items-center justify-between","data-gufi-src":"components/DocumentoFirma.tsx:286"},__gh("span",{className:"text-[13px] text-[#8d8a7f]","data-gufi-src":"components/DocumentoFirma.tsx:287"},"Tu firma"),hayFirma&&__gh("button",{type:"button",onClick:borrar,className:"inline-flex items-center gap-1 text-[13px] text-[#54524a]","data-gufi-src":"components/DocumentoFirma.tsx:289"},__gh(import_lucide_react.RefreshCw,{className:"w-3.5 h-3.5"})," Repetir")),__gh("canvas",{ref:lienzo,className:`w-full h-[150px] mt-2 rounded-xl border bg-white touch-none block ${err("firma")?"border-[#b42318]":"border-[#e4e0d7]"}`,onPointerDown:empezar,onPointerMove:mover,onPointerUp:soltar,onPointerCancel:soltar,"data-gufi-src":"components/DocumentoFirma.tsx:294"}),__gh("label",{className:"flex items-start gap-2.5 mt-4 text-[14px] text-[#54524a]","data-gufi-src":"components/DocumentoFirma.tsx:302"},__gh("input",{type:"checkbox",checked:acepto,onChange:e=>setAcepto(e.target.checked),className:"mt-1 w-4 h-4 accent-[#1d4a3e]","data-gufi-src":"components/DocumentoFirma.tsx:303"}),__gh("span",{"data-gufi-src":"components/DocumentoFirma.tsx:304"},"He le\xEDdo el documento y lo firmo con estos datos.")),aviso&&__gh("p",{className:"text-[13.5px] text-[#b42318] mt-3","data-gufi-src":"components/DocumentoFirma.tsx:306"},aviso),__gh("button",{type:"button",onClick:firmar,disabled:enviando,className:"mt-4 w-full h-12 rounded-xl text-white text-[16px] font-medium inline-flex items-center justify-center gap-2 disabled:opacity-60",style:{background:ACCENT},"data-gufi-src":"components/DocumentoFirma.tsx:307"},enviando?__gh(import_lucide_react.Loader2,{className:"w-4 h-4 animate-spin"}):null,"Firmar"),__gh("p",{className:"text-[12px] text-[#8d8a7f] mt-3 leading-relaxed","data-gufi-src":"components/DocumentoFirma.tsx:317"},"Al firmar se guardan contigo tu firma, la fecha y hora, la direcci\xF3n IP y el navegador, y recibes una copia en PDF."))))}var COMPANY_ID=null;function fijarEmpresa(gufi){let n=Number(gufi?.siteInfo?.company_id??gufi?.context?.activeCompany?.id);if(!Number.isInteger(n)||n<=0)throw new Error("Este sitio no sabe de qu\xE9 empresa es");COMPANY_ID=n}var API_BASE=typeof window<"u"&&window.location.hostname==="localhost"?"http://localhost:3000":"";async function llamar(name,body){if(COMPANY_ID===null)throw new Error("Se llam\xF3 a la firma antes de saber la empresa");let res=await fetch(`${API_BASE}/api/public/${COMPANY_ID}/automation/${name}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(body)}),json=await res.json().catch(()=>({}));if(!res.ok||json&&json.success===!1)throw new Error(json&&(json.error||json.message)||`No ha salido (${res.status})`);return json&&typeof json=="object"&&"result"in json?json.result:json}function FirmaDocumentos({gufi}){let[token]=(0,import_react2.useState)(()=>typeof window>"u"?"":(new URLSearchParams(window.location.search).get("d")||"").trim());fijarEmpresa(gufi);let[marca,setMarca]=(0,import_react2.useState)(null),[errorMarca,setErrorMarca]=(0,import_react2.useState)("");(0,import_react2.useEffect)(()=>{llamar("portal_marca",{}).then(setMarca).catch(e=>setErrorMarca(String(e&&e.message||e)))},[]);let fondo={minHeight:"100vh",display:"grid",placeItems:"center",padding:24,background:"#faf9f6",fontFamily:"-apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif"};return errorMarca?__gh("main",{style:fondo,"data-gufi-src":"page.tsx:63"},__gh("p",{style:{fontSize:15,color:"#54524a"},"data-gufi-src":"page.tsx:63"},"No se ha podido abrir la p\xE1gina: ",errorMarca)):marca?token?__gh(DocumentoFirma,{token,llamar,marca}):__gh("main",{style:fondo,"data-gufi-src":"page.tsx:67"},__gh("div",{style:{maxWidth:420,textAlign:"center",display:"flex",flexDirection:"column",alignItems:"center"},"data-gufi-src":"page.tsx:68"},__gh(LogoMarca,{marca,tam:56}),__gh("h1",{style:{fontFamily:"Georgia, 'Times New Roman', serif",fontWeight:400,fontSize:26,color:"#16150f",margin:"18px 0 0"},"data-gufi-src":"page.tsx:70"},"Firma de documentos"),__gh("p",{style:{fontSize:15,lineHeight:1.6,color:"#54524a",margin:"12px 0 0"},"data-gufi-src":"page.tsx:71"},"Para firmar, abre el enlace que te ha mandado ",marca.nombre,". Si no lo encuentras, p\xEDdenoslo y te lo enviamos otra vez."))):__gh("main",{style:fondo,"data-gufi-src":"page.tsx:64"})}var stdin_default=FirmaDocumentos;