import{D as j}from"./drawflow.min-C16_fI-g.js";import{g as x}from"./api-DZ3cXm1m.js";import"./vendor-C0v32J92.js";let B=0;function C(){return`node_${Date.now()}_${++B}`}function D(t,n){if(t==="condition"){if(n==="output_1")return"true";if(n==="output_2")return"false"}return"default"}function q(t,n){var e;const o=[],r=t.drawflow.Home.data;for(const s in r){const a=r[s],i=a.outputs||{};for(const c in i){const d=D((e=a.data)==null?void 0:e.type,c);if(!d)continue;const l=i[c].connections||[];for(const p of l){const v=n.get(parseInt(s,10)),b=n.get(parseInt(p.node,10));!v||!b||o.push({from_client_id:v,to_client_id:b,source_port:d})}}}return o}function M(t){var a,i,c;const n=t.export(),o=new Map,r=n.drawflow.Home.data,e=[];for(const d in r){const l=r[d],p=((a=l.data)==null?void 0:a.client_id)||C();o.set(parseInt(d,10),p),e.push({client_id:p,type:((i=l.data)==null?void 0:i.type)||"action",config:((c=l.data)==null?void 0:c.config)||{},position_x:Math.round(l.pos_x||0),position_y:Math.round(l.pos_y||0)})}const s=q(n,o);return{nodes:e,edges:s}}const S=()=>window.workflowBuilderConfig;function m(t){return t==null?"":String(t).replace(/[&<>"']/g,n=>({"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;","'":"&#39;"})[n])}function T(t,n,o={}){const r=S().translations||{},e=S().triggerEvents||{},s=S().actionTypes||{};let a="",i="";switch(t){case"trigger":a=`<i class="fas fa-bolt"></i> ${m(e[o.event]||r.choose_trigger||"Trigger")}`,i=o.event?m(o.event):"";break;case"condition":a=`<i class="fas fa-code-branch"></i> ${m(r.condition_field||"Condition")}`,i=o.field?`${m(o.field)} ${m(o.operator||"=")} ${m(String(o.value??""))}`:"";break;case"action":a=`<i class="fas fa-bolt"></i> ${m(s[n]||n||"Action")}`,i="";break;case"chain":a=`<i class="fas fa-link"></i> ${m(r.chain_label||"Chain")}`,i=o.target_workflow_id?`&rarr; #${m(String(o.target_workflow_id))}`:"";break}return`<div class="node-title">${a}</div>${i?`<div class="node-subtitle">${i}</div>`:""}`}function L(t){return t==="trigger"?{inputs:0,outputs:1}:t==="condition"?{inputs:1,outputs:2}:{inputs:1,outputs:1}}function H(t,n){return t==="trigger"?{event:""}:t==="condition"?{field:"",operator:"equals",value:""}:t==="action"?{action_type:n,parameters:{}}:t==="chain"?{target_workflow_id:null,dry_run:!1}:{}}const _=()=>window.workflowBuilderConfig;function f(t){return t==null?"":String(t).replace(/[&<>"']/g,n=>({"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;","'":"&#39;"})[n])}function $(t){return f(t)}function I(t,n){var i,c,d;const o=document.getElementById("workflow-config-form"),r=document.getElementById("workflow-config-empty");if(!t){r&&r.classList.remove("d-none"),o&&(o.classList.add("d-none"),o.innerHTML="");return}if(r&&r.classList.add("d-none"),!o)return;o.classList.remove("d-none");const e=(i=t.data)==null?void 0:i.type,s=((c=t.data)==null?void 0:c.config)||{};let a="";switch(e){case"trigger":a=O(s);break;case"condition":a=R(s);break;case"action":a=A((d=t.data)==null?void 0:d.subtype,s);break;case"chain":a=F(s);break}o.innerHTML=a,o.querySelectorAll("[data-config-key]").forEach(l=>{l.addEventListener("input",()=>{const p=l.dataset.configKey,v=l.type==="checkbox"?l.checked:l.value;n(p,v)})}),e==="chain"&&J(s.target_workflow_id)}function O(t){const n=_().triggerEvents||{};return`
        <div class="mb-3">
            <label class="form-label small">Event</label>
            <select class="form-select form-select-sm" data-config-key="event">
                <option value="">&mdash;</option>
                ${Object.entries(n).map(([r,e])=>`<option value="${$(r)}" ${t.event===r?"selected":""}>${f(e)}</option>`).join("")}
            </select>
        </div>`}function R(t){const n=_().translations||{},r=["equals","not_equals","greater_than","less_than","contains","in","not_in"].map(e=>`<option value="${e}" ${t.operator===e?"selected":""}>${e}</option>`).join("");return`
        <div class="mb-3">
            <label class="form-label small">${f(n.condition_field||"Field")}</label>
            <input type="text" class="form-control form-control-sm" data-config-key="field" value="${$(t.field||"")}" placeholder="status">
        </div>
        <div class="mb-3">
            <label class="form-label small">${f(n.condition_operator||"Operator")}</label>
            <select class="form-select form-select-sm" data-config-key="operator">${r}</select>
        </div>
        <div class="mb-3">
            <label class="form-label small">${f(n.condition_value||"Value")}</label>
            <input type="text" class="form-control form-control-sm" data-config-key="value" value="${$(t.value??"")}">
        </div>`}function A(t,n){return`
        <div class="mb-3">
            <label class="form-label small">Action Type</label>
            <input type="text" class="form-control form-control-sm" value="${$(t||n.action_type||"")}" disabled>
        </div>
        <div class="mb-3">
            <label class="form-label small">Parameters (JSON)</label>
            <textarea class="form-control form-control-sm font-monospace" rows="6" data-config-key="parameters_json"
                placeholder='{"key": "value"}'>${f(JSON.stringify(n.parameters||{},null,2))}</textarea>
            <div class="form-text small">Will be parsed as JSON on save.</div>
        </div>`}function F(t){const n=_().translations||{};return`
        <div class="mb-3">
            <label class="form-label small">${f(n.choose_chain_target||"Target Workflow")}</label>
            <select class="form-select form-select-sm" data-config-key="target_workflow_id" id="chain-target-select">
                <option value="">${f(n.choose_chain_target||"—")}</option>
            </select>
        </div>
        <div class="mb-3 form-check">
            <input type="checkbox" class="form-check-input" id="chain-dry-run" data-config-key="dry_run" ${t.dry_run?"checked":""}>
            <label for="chain-dry-run" class="form-check-label small">Dry run only</label>
        </div>`}async function J(t){var r;const n=(r=_().routes)==null?void 0:r.chainTargets;if(!n)return;const o=n+(_().workflowId?`?exclude_id=${_().workflowId}`:"");try{const s=await(await fetch(o,{headers:{Accept:"application/json",Authorization:`Bearer ${x()}`}})).json(),a=document.getElementById("chain-target-select");if(!a)return;const i=(s.workflows||[]).map(c=>`<option value="${c.id}" ${String(t)===String(c.id)?"selected":""}>${f(c.name)} (${f(c.trigger_event)})</option>`).join("");a.insertAdjacentHTML("beforeend",i)}catch(e){console.error("Failed to load chain targets",e)}}const N=()=>window.workflowBuilderConfig;function y(t){return t==null?"":String(t).replace(/[&<>"']/g,n=>({"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;","'":"&#39;"})[n])}async function P(){var e,s,a;const t=N().translations||{},n=(e=N().routes)==null?void 0:e.dryRun;if(!n){alert("Save the workflow first before running a dry-run.");return}const o=document.getElementById("dry-run-result");o&&(o.innerHTML=`<div class="text-center text-muted py-3"><i class="fas fa-spinner fa-spin"></i> ${y(t.dry_run_running||"Running...")}</div>`);const r=document.getElementById("dryRunModal");r&&((s=window.bootstrap)!=null&&s.Modal)&&new window.bootstrap.Modal(r).show();try{const i=((a=document.querySelector('meta[name="csrf-token"]'))==null?void 0:a.content)||"",d=await(await fetch(n,{method:"POST",headers:{Accept:"application/json","Content-Type":"application/json","X-CSRF-TOKEN":i,"X-Requested-With":"XMLHttpRequest"},body:JSON.stringify({})})).json();if(!d.success){o&&(o.innerHTML=`<div class="alert alert-danger">${y(t.dry_run_error||"Dry-run failed")}</div>`);return}X(d.nodes_executed||[])}catch(i){o&&(o.innerHTML=`<div class="alert alert-danger">${y(t.dry_run_error||"Dry-run failed")}: ${y(i.message)}</div>`)}}function X(t){const n=document.getElementById("dry-run-result");if(!n)return;if(!t.length){n.innerHTML='<div class="text-muted">No nodes executed.</div>';return}const o=t.map(r=>`
        <tr>
            <td><code>${y(r.node_id??"?")}</code></td>
            <td>${y(r.type??"?")}</td>
            <td>${y(r.status??"?")}</td>
            <td><pre class="small mb-0">${y(JSON.stringify(r.result??{},null,2))}</pre></td>
        </tr>`).join("");n.innerHTML=`
        <table class="table table-sm">
            <thead><tr><th>Node</th><th>Type</th><th>Status</th><th>Result</th></tr></thead>
            <tbody>${o}</tbody>
        </table>`}const g=()=>window.workflowBuilderConfig;let u=null,w=null;document.addEventListener("DOMContentLoaded",W);function W(){var n,o,r;const t=document.getElementById("drawflow");t&&(u=new j(t),u.reroute=!0,u.start(),document.querySelectorAll(".workflow-node-template").forEach(e=>{e.setAttribute("draggable","true"),e.addEventListener("dragstart",s=>{s.dataTransfer.setData("text/plain",JSON.stringify({type:e.dataset.type,subtype:e.dataset.subtype||null}))})}),t.addEventListener("dragover",e=>e.preventDefault()),t.addEventListener("drop",e=>{e.preventDefault();const s=e.dataTransfer.getData("text/plain");if(!s)return;let a;try{a=JSON.parse(s)}catch{return}U(a.type,a.subtype,e.clientX,e.clientY)}),u.on("nodeSelected",e=>{w=e;const s=u.getNodeFromId(e);I(s,(a,i)=>K(a,i))}),u.on("nodeUnselected",()=>{w=null,I(null)}),u.on("nodeRemoved",()=>{w=null,I(null)}),(n=document.getElementById("btn-save-workflow"))==null||n.addEventListener("click",G),(o=document.getElementById("btn-dry-run"))==null||o.addEventListener("click",P),g().mode==="edit"&&((r=g().routes)!=null&&r.graph)&&z())}function U(t,n,o,r){const e=L(t),s=H(t,n),a={type:t,subtype:n,config:s,client_id:C()},i=T(t,n,s),c=document.getElementById("drawflow").getBoundingClientRect(),d=o-c.left,l=r-c.top;u.addNode(t,e.inputs,e.outputs,d,l,t,a,i)}function K(t,n){var i;if(!w)return;const o=u.getNodeFromId(w);if(!o)return;const r={...((i=o.data)==null?void 0:i.config)||{}};if(t==="parameters_json")try{r.parameters=JSON.parse(n||"{}")}catch{return}else r[t]=n;const e={...o.data,config:r};u.updateNodeDataFromId(w,e);const s=T(e.type,e.subtype,r),a=document.querySelector(`#node-${w} .drawflow_content_node`);a&&(a.innerHTML=s)}async function z(){var t;try{const o=await(await fetch(g().routes.graph,{headers:{Accept:"application/json",Authorization:`Bearer ${x()}`}})).json();if(!o.success)return;const r=new Map;for(const e of o.nodes||[]){const s=L(e.type),a={type:e.type,subtype:((t=e.config)==null?void 0:t.action_type)||null,config:e.config||{},client_id:`db_${e.id}`},i=T(e.type,a.subtype,e.config),c=u.addNode(e.type,s.inputs,s.outputs,e.position_x,e.position_y,e.type,a,i);r.set(e.id,c)}for(const e of o.edges||[]){const s=r.get(e.from_node_id),a=r.get(e.to_node_id);if(!s||!a)continue;let i="output_1";e.source_port==="false"&&(i="output_2"),u.addConnection(s,a,i,"input_1")}}catch(n){console.error("Failed to load graph",n)}}async function G(){var p,v,b,E;const t=g().translations||{},n=document.getElementById("wf-name"),o=document.getElementById("wf-trigger-event"),r=((n==null?void 0:n.value)||"").trim(),e=(o==null?void 0:o.value)||"";if(!r){alert(t.validation_name_required||"Name required");return}if(!e){alert(t.validation_trigger_required||"Trigger required");return}const s=M(u);if(!s.nodes.some(h=>h.type==="trigger")){alert(t.validation_no_trigger||"Workflow must have a trigger node");return}const i={name:r,description:((p=document.getElementById("wf-description"))==null?void 0:p.value)||"",trigger_event:e,is_active:!!((v=document.getElementById("wf-is-active"))!=null&&v.checked),priority:parseInt((b=document.getElementById("wf-priority"))==null?void 0:b.value,10)||0,nodes:s.nodes,edges:s.edges},c=g().mode==="edit"?g().routes.saveUpdate:g().routes.saveCreate,d=g().mode==="edit"?"PUT":"POST",l=((E=document.querySelector('meta[name="csrf-token"]'))==null?void 0:E.content)||"";try{const h=await fetch(c,{method:d,headers:{Accept:"application/json","Content-Type":"application/json","X-CSRF-TOKEN":l,"X-Requested-With":"XMLHttpRequest"},body:JSON.stringify(i)}),k=await h.json();if(!h.ok||!k.success){console.error("Save failed",k),alert(t.save_error||"Save failed");return}window.location.href=k.redirect||g().routes.index}catch(h){console.error("Save error",h),alert((t.save_error||"Save failed")+": "+h.message)}}
