<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8"/>
<meta name="viewport" content="width=device-width,initial-scale=1,viewport-fit=cover"/>
<title>Form</title>
<script src="https://cdnjs.cloudflare.com/ajax/libs/signature_pad/4.1.7/signature_pad.umd.min.js"></script>
<link href="https://fonts.googleapis.com/css2?family=DM+Sans:opsz,wght@9..40,300;9..40,400;9..40,500;9..40,600&display=swap" rel="stylesheet"/>
<style>
/* ── Design tokens ── */
:root{
  --ac:#2563eb;--ac-dark:#1d4ed8;--ac-light:#eff6ff;--ac-ring:rgba(37,99,235,.15);
  --green:#059669;--green-light:#ecfdf5;
  --red:#dc2626;--red-light:#fef2f2;
  --ink:#111217;--sub:#4b5563;--muted:#9ca3af;
  --border:#e5e7eb;--border2:rgba(0,0,0,.1);
  --bg:#f5f4f1;--white:#fff;
  --r8:8px;--r10:10px;--r12:12px;--r16:16px;--r20:20px;
  --font:'DM Sans',sans-serif;
}
*{box-sizing:border-box;margin:0;padding:0}
body{font-family:var(--font);-webkit-font-smoothing:antialiased;background:var(--bg);
  min-height:100vh;color:var(--ink);padding-bottom:env(safe-area-inset-bottom,0px)}

/* ── Layout ── */
.form-wrap{max-width:640px;margin:0 auto;padding:32px 16px 64px}
.form-card{background:var(--white);border-radius:var(--r20);
  box-shadow:0 1px 3px rgba(0,0,0,.06),0 8px 32px rgba(0,0,0,.07);overflow:hidden}

/* ── Header ── */
.form-hdr{
  background:linear-gradient(135deg,var(--ac) 0%,var(--ac-dark) 100%);
  padding:32px 28px 26px;color:#fff;position:relative;overflow:hidden;
}
.form-hdr::before{
  content:'';position:absolute;top:-40px;right:-40px;width:160px;height:160px;
  background:rgba(255,255,255,.06);border-radius:50%;pointer-events:none;
}
.form-hdr::after{
  content:'';position:absolute;bottom:-30px;left:50px;width:100px;height:100px;
  background:rgba(255,255,255,.04);border-radius:50%;pointer-events:none;
}
.form-hdr h1{font-size:clamp(18px,4vw,24px);font-weight:600;margin-bottom:5px;line-height:1.2;position:relative}
.form-hdr p{font-size:14px;opacity:.8;line-height:1.55;position:relative;margin-top:4px}
.form-hdr-logo{width:36px;height:36px;background:rgba(255,255,255,.18);border-radius:9px;
  display:flex;align-items:center;justify-content:center;margin-bottom:14px;position:relative}
.form-hdr-logo svg{width:18px;height:18px;stroke:#fff;fill:none;stroke-width:2;stroke-linecap:round;stroke-linejoin:round}

/* ── Body ── */
.form-body{padding:28px}

/* ── Fields ── */
.field{margin-bottom:20px}
.field label{display:flex;align-items:center;gap:4px;font-size:12px;font-weight:600;
  color:var(--sub);text-transform:uppercase;letter-spacing:.05em;margin-bottom:7px}
.field label .req{color:var(--red);font-size:11px}
.field input,.field select,.field textarea{
  width:100%;border:1.5px solid var(--border);border-radius:var(--r10);
  padding:11px 14px;font-size:14px;color:var(--ink);outline:none;
  transition:border .15s,box-shadow .15s;font-family:var(--font);background:var(--white);
  appearance:none;-webkit-appearance:none;
}
.field select{background-image:url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='12' height='12' viewBox='0 0 24 24' fill='none' stroke='%236b7280' stroke-width='2' stroke-linecap='round' stroke-linejoin='round'%3E%3Cpolyline points='6 9 12 15 18 9'/%3E%3C/svg%3E");background-repeat:no-repeat;background-position:right 14px center;padding-right:36px}
.field input:focus,.field select:focus,.field textarea:focus{
  border-color:var(--ac);box-shadow:0 0 0 3px var(--ac-ring);background:var(--white)}
.field textarea{resize:vertical;min-height:96px;line-height:1.55}
.field input[type=date]{color-scheme:light}
.field .err{font-size:12px;color:var(--red);margin-top:5px;display:none}
.field.has-err input,.field.has-err select,.field.has-err textarea{border-color:var(--red)}
.field.has-err .err{display:block}
.field-hint{font-size:11px;color:var(--muted);margin-top:4px}

/* ── Radio & Checkbox ── */
.opt-list{display:flex;flex-direction:column;gap:7px}
.opt-item{
  display:flex;align-items:center;gap:12px;cursor:pointer;
  padding:11px 14px;border:1.5px solid var(--border);border-radius:var(--r10);
  transition:border .15s,background .15s,box-shadow .15s;user-select:none;
}
.opt-item:hover{border-color:var(--ac);background:var(--ac-light)}
.opt-item:has(input:checked){border-color:var(--ac);background:var(--ac-light);box-shadow:0 0 0 2px var(--ac-ring)}
.opt-item input{width:17px;height:17px;accent-color:var(--ac);flex-shrink:0;cursor:pointer}
.opt-item span{font-size:14px;color:var(--ink);font-weight:400}

/* ── File upload ── */
.file-zone{
  border:2px dashed var(--border);border-radius:var(--r12);padding:28px 20px;
  text-align:center;cursor:pointer;transition:all .18s;position:relative;
}
.file-zone:hover,.file-zone.drag{border-color:var(--ac);background:var(--ac-light)}
.file-zone svg{width:32px;height:32px;stroke:var(--muted);fill:none;stroke-width:1.5;stroke-linecap:round;stroke-linejoin:round;display:block;margin:0 auto 10px}
.file-zone .fz-title{font-size:14px;font-weight:500;color:var(--sub);margin-bottom:3px}
.file-zone .fz-sub{font-size:12px;color:var(--muted)}
.file-zone input[type=file]{position:absolute;inset:0;opacity:0;cursor:pointer;width:100%;height:100%}
.file-list{margin-top:10px;display:flex;flex-direction:column;gap:5px}
.file-item{
  display:flex;align-items:center;gap:9px;background:#f9fafb;
  border:1px solid var(--border);border-radius:var(--r8);padding:9px 12px;font-size:13px;
}
.file-item svg{width:15px;height:15px;stroke:var(--ac);fill:none;stroke-width:2;stroke-linecap:round;stroke-linejoin:round;flex-shrink:0}
.file-item span{flex:1;color:var(--sub);overflow:hidden;text-overflow:ellipsis;white-space:nowrap}
.file-item .rm{width:22px;height:22px;border:none;background:none;cursor:pointer;
  color:var(--muted);display:flex;align-items:center;justify-content:center;border-radius:5px;flex-shrink:0}
.file-item .rm:hover{background:var(--red-light);color:var(--red)}

/* ── Signature ── */
.sig-wrap{border:1.5px solid var(--border);border-radius:var(--r12);overflow:hidden;background:#fafafa;position:relative}
.sig-wrap canvas{display:block;width:100%;height:160px;cursor:crosshair;touch-action:none}
.sig-actions{display:flex;justify-content:flex-end;padding:8px 12px;background:var(--white);border-top:1px solid var(--border);gap:8px;align-items:center}
.sig-hint{font-size:11px;color:var(--muted);flex:1}
.sig-clear{font-size:12px;font-weight:500;color:var(--muted);border:1px solid var(--border);background:var(--white);cursor:pointer;padding:5px 11px;border-radius:7px;font-family:var(--font);transition:all .15s}
.sig-clear:hover{background:var(--red-light);color:var(--red);border-color:#fca5a5}

/* ── Password gate ── */
.pw-gate{padding:36px 28px;text-align:center}
.pw-gate .pw-icon{width:52px;height:52px;background:var(--ac-light);border-radius:14px;display:flex;align-items:center;justify-content:center;margin:0 auto 16px}
.pw-gate .pw-icon svg{width:22px;height:22px;stroke:var(--ac);fill:none;stroke-width:2;stroke-linecap:round;stroke-linejoin:round}
.pw-gate h2{font-size:18px;font-weight:600;color:var(--ink);margin-bottom:6px}
.pw-gate p{font-size:14px;color:var(--sub);margin-bottom:22px;line-height:1.55}
.pw-gate input{max-width:280px;width:100%;border:1.5px solid var(--border);border-radius:var(--r10);padding:12px 16px;font-size:15px;text-align:center;outline:none;font-family:var(--font);color:var(--ink);transition:all .15s}
.pw-gate input:focus{border-color:var(--ac);box-shadow:0 0 0 3px var(--ac-ring)}
#pw-err{font-size:12px;color:var(--red);margin-top:8px;display:none}

/* ── Submit button ── */
.btn-submit{
  width:100%;padding:14px 20px;background:var(--ac);color:#fff;
  font-size:14px;font-weight:600;border:none;border-radius:var(--r10);
  cursor:pointer;transition:all .18s;margin-top:6px;font-family:var(--font);
  display:flex;align-items:center;justify-content:center;gap:8px;letter-spacing:.01em;
}
.btn-submit:hover:not(:disabled){background:var(--ac-dark);transform:translateY(-1px);box-shadow:0 4px 16px rgba(37,99,235,.3)}
.btn-submit:disabled{opacity:.55;cursor:not-allowed;transform:none;box-shadow:none}

/* ── Success ── */
.success-box{padding:52px 28px;text-align:center}
.success-icon{width:72px;height:72px;background:linear-gradient(135deg,#10b981,#059669);
  border-radius:50%;display:flex;align-items:center;justify-content:center;margin:0 auto 18px;
  box-shadow:0 8px 24px rgba(5,150,105,.25)}
.success-icon svg{width:34px;height:34px;stroke:#fff;fill:none;stroke-width:2.5;stroke-linecap:round;stroke-linejoin:round}
.success-box h2{font-size:22px;font-weight:600;color:var(--ink);margin-bottom:7px}
.success-box p{font-size:14px;color:var(--sub);line-height:1.6;margin-bottom:4px}
.success-ref{display:inline-flex;align-items:center;gap:6px;margin-top:16px;
  background:var(--bg);border:1px solid var(--border);border-radius:8px;
  padding:7px 14px;font-size:12px;font-family:monospace;color:var(--muted)}

/* ── Global error ── */
.global-err{background:var(--red-light);border:1px solid #fca5a5;border-radius:var(--r10);
  padding:13px 16px;color:#991b1b;font-size:13px;margin-bottom:18px;
  display:none;align-items:flex-start;gap:8px}
.global-err.show{display:flex}
.global-err svg{width:15px;height:15px;stroke:currentColor;fill:none;stroke-width:2;stroke-linecap:round;flex-shrink:0;margin-top:1px}

/* ── Spinner ── */
.spinner{display:inline-block;width:17px;height:17px;border:2px solid rgba(255,255,255,.35);
  border-top-color:#fff;border-radius:50%;animation:spin .7s linear infinite;flex-shrink:0}
@keyframes spin{to{transform:rotate(360deg)}}

/* ── Multi-step progress ── */
.step-bar{display:flex;align-items:center;margin-bottom:24px}
.sdot{width:28px;height:28px;border-radius:50%;display:flex;align-items:center;justify-content:center;
  font-size:11px;font-weight:600;border:2px solid var(--border);color:var(--muted);
  background:var(--white);flex-shrink:0;transition:all .22s;line-height:1}
.sdot.active{border-color:var(--ac);background:var(--ac);color:#fff;box-shadow:0 2px 8px var(--ac-ring)}
.sdot.done{border-color:var(--green);background:var(--green);color:#fff}
.sline{flex:1;height:2px;background:var(--border);transition:background .22s;margin:0 -1px}
.sline.done{background:var(--green)}
.step-btns{display:flex;gap:10px;margin-top:18px;padding-top:18px;border-top:1px solid var(--border)}
.step-back{flex:1;padding:12px;background:var(--white);color:var(--sub);font-size:14px;
  font-weight:500;border:1.5px solid var(--border);border-radius:var(--r10);cursor:pointer;
  font-family:var(--font);transition:all .15s;display:flex;align-items:center;justify-content:center;gap:6px}
.step-back:hover{border-color:var(--ac);color:var(--ac);background:var(--ac-light)}
.step-next{flex:2;padding:12px;background:var(--ac);color:#fff;font-size:14px;
  font-weight:600;border:none;border-radius:var(--r10);cursor:pointer;font-family:var(--font);
  transition:all .18s;display:flex;align-items:center;justify-content:center;gap:6px}
.step-next:hover{background:var(--ac-dark);box-shadow:0 4px 14px rgba(37,99,235,.28)}

/* ── 2-column field grid ── */
.fields-grid{display:grid;grid-template-columns:1fr 1fr;gap:0 18px}
.field.f-full{grid-column:1/-1}
.field.f-half{grid-column:span 1}

/* ── Loading ── */
.ld{display:flex;flex-direction:column;align-items:center;justify-content:center;padding:72px 24px;gap:14px;color:var(--muted)}
.ld-spin{width:32px;height:32px;border:2.5px solid var(--border);border-top-color:var(--ac);border-radius:50%;animation:spin .7s linear infinite}

/* ── Responsive ── */
@media(max-width:600px){
  .form-wrap{padding:0 0 56px}
  .form-card{border-radius:0;box-shadow:none;min-height:100vh}
  .form-hdr{padding:28px 20px 22px;border-radius:0}
  .form-body{padding:22px 18px}
  .field input,.field select,.field textarea{font-size:16px} /* prevent iOS zoom */
  .fields-grid{grid-template-columns:1fr!important}
  .field.f-half{grid-column:1/-1!important}
  .opt-item{padding:10px 13px}
  .sig-wrap canvas{height:140px}
  .success-box{padding:44px 20px}
  .success-icon{width:64px;height:64px}
  .success-icon svg{width:30px;height:30px}
}
@media(max-width:380px){
  .form-hdr{padding:22px 16px 18px}
  .form-body{padding:18px 14px}
}

/* ── Fade animation ── */
.fade-in{animation:fadeIn .32s ease both}
@keyframes fadeIn{from{opacity:0;transform:translateY(6px)}to{opacity:1;transform:none}}
</style>
</head>
<body>
<div class="form-wrap">
  <div class="form-card" id="card">
    <div class="ld"><div class="ld-spin"></div><span style="font-size:13px">Loading form…</span></div>
  </div>
</div>

<script>
const BASE = (()=>{const p=window.location.pathname;return p.endsWith('/')?p.slice(0,-1):p.substring(0,p.lastIndexOf('/'));})();
const API  = BASE+'/api';
const slug = new URLSearchParams(location.search).get('s')||'';
let FORM=null, FIELDS=[], pads={}, fileSelections={};
let _steps=[], _curStep=0, _stepData={};

function esc(s){return String(s||'').replace(/&/g,'&amp;').replace(/</g,'&lt;').replace(/>/g,'&gt;');}

async function loadForm(){
  if(!slug){renderError('No form specified.'); return;}
  try{
    const r=await fetch(API+'/public/forms/'+slug);
    const j=await r.json();
    if(!j.ok){renderError('Form not found.'); return;}
    FORM=j.form; FIELDS=FORM.fields||[];
    document.title=FORM.title;
    if(FORM.requires_password) renderPasswordGate();
    else renderForm();
  }catch(e){renderError('Could not load form.');}
}

function renderError(msg){
  document.getElementById('card').innerHTML=`<div style="padding:60px 28px;text-align:center">
    <div style="width:52px;height:52px;background:#fef2f2;border-radius:14px;display:flex;align-items:center;justify-content:center;margin:0 auto 16px">
      <svg width="22" height="22" viewBox="0 0 24 24" style="stroke:#dc2626;fill:none;stroke-width:2;stroke-linecap:round"><circle cx="12" cy="12" r="10"/><line x1="12" y1="8" x2="12" y2="12"/><line x1="12" y1="16" x2="12.01" y2="16"/></svg>
    </div>
    <div style="font-size:15px;font-weight:500;color:#111217;margin-bottom:6px">Form Unavailable</div>
    <div style="font-size:13px;color:#6b7280">${esc(msg)}</div>
  </div>`;
}

function renderPasswordGate(){
  document.getElementById('card').innerHTML=`
    <div class="form-hdr fade-in">
      <div class="form-hdr-logo"><svg viewBox="0 0 24 24"><rect x="3" y="3" width="18" height="18" rx="2"/><path d="M3 9h18M9 21V9"/></svg></div>
      <h1>${esc(FORM.title)}</h1>${FORM.description?`<p>${esc(FORM.description)}</p>`:''}
    </div>
    <div class="pw-gate fade-in">
      <div class="pw-icon"><svg viewBox="0 0 24 24"><rect x="3" y="11" width="18" height="11" rx="2" ry="2"/><path d="M7 11V7a5 5 0 0 1 10 0v4"/></svg></div>
      <h2>Password Required</h2>
      <p>This form is password protected. Enter the password to continue.</p>
      <input type="password" id="pw-input" placeholder="Enter password" onkeydown="if(event.key==='Enter')checkPW()"/>
      <div id="pw-err">Incorrect password. Please try again.</div>
      <button class="btn-submit" style="margin-top:16px;max-width:280px" onclick="checkPW()">
        <svg width="15" height="15" viewBox="0 0 24 24" style="stroke:#fff;fill:none;stroke-width:2;stroke-linecap:round"><polyline points="9 18 15 12 9 6"/></svg>
        Continue
      </button>
    </div>`;
}

async function checkPW(){
  const pw=document.getElementById('pw-input').value;
  const fd=new FormData(); fd.append('_form_password',pw);
  // test with empty submit
  const r=await fetch(API+'/submit/'+slug,{method:'POST',body:fd});
  const j=await r.json();
  if(j.error==='Incorrect form password'||r.status===403){
    document.getElementById('pw-err').style.display='block'; return;
  }
  window._formPW=pw; renderForm();
}

function buildSteps(){
  _steps=[];let cur=[];
  FIELDS.forEach(f=>{
    if(f.type==='page-break'){_steps.push({label:f.label||'Next Step',fields:cur});cur=[];}
    else cur.push(f);
  });
  _steps.push({label:FORM.submit_label||'Submit',fields:cur});
}

function renderFieldHtml(f){
  const req=f.required?`<span class="req">*</span>`:'';
  const wCls=f.width==='half'?'f-half':'f-full';
  let inner='';
  const prev=_stepData[f.id]||'';
  switch(f.type){
    case 'text': case 'email': case 'phone': case 'number': case 'date':
      inner=`<input type="${f.type==='phone'?'tel':f.type}" name="${f.id}" placeholder="${esc(f.placeholder||'')}" value="${esc(prev)}" ${f.required?'required':''}/>`; break;
    case 'textarea':
      inner=`<textarea name="${f.id}" placeholder="${esc(f.placeholder||'')}" rows="4" ${f.required?'required':''}>${esc(prev)}</textarea>`; break;
    case 'select':
      inner=`<select name="${f.id}" ${f.required?'required':''}><option value="">— Select —</option>${(f.options||[]).map(o=>`<option value="${esc(o)}"${prev===o?' selected':''}>${esc(o)}</option>`).join('')}</select>`; break;
    case 'radio':
      inner=`<div class="opt-list">${(f.options||[]).map((o,i)=>`
        <label class="opt-item"><input type="radio" name="${f.id}" value="${esc(o)}" ${prev===o?'checked':''} ${i===0&&f.required?'required':''}/><span>${esc(o)}</span></label>`).join('')}</div>`; break;
    case 'checkbox':
      const prevArr=Array.isArray(prev)?prev:[];
      inner=`<div class="opt-list">${(f.options||[]).map(o=>`
        <label class="opt-item"><input type="checkbox" name="${f.id}[]" value="${esc(o)}"${prevArr.includes(o)?' checked':''}/><span>${esc(o)}</span></label>`).join('')}</div>`; break;
    case 'file':
      inner=`<div class="file-zone" id="fz-${f.id}"
        onclick="document.getElementById('fi-${f.id}').click()"
        ondragover="event.preventDefault();this.classList.add('drag')"
        ondragleave="this.classList.remove('drag')"
        ondrop="event.preventDefault();this.classList.remove('drag');handleFiles('${f.id}',null,event.dataTransfer.files)">
        <svg viewBox="0 0 24 24"><polyline points="16 16 12 12 8 16"/><line x1="12" y1="12" x2="12" y2="21"/><path d="M20.39 18.39A5 5 0 0 0 18 9h-1.26A8 8 0 1 0 3 16.3"/></svg>
        <div class="fz-title">Click or drag &amp; drop to upload</div>
        <div class="fz-sub">Max ${(window._maxMB||10)}MB per file${f.multiple?' · Multiple files allowed':''}</div>
        <input type="file" id="fi-${f.id}" name="${f.id}" ${f.multiple?'multiple':''} style="display:none" onchange="handleFiles('${f.id}',this)"/>
      </div><div class="file-list" id="fl-${f.id}"></div>`; break;
    case 'signature':
      inner=`<div class="sig-wrap"><canvas id="sc-${f.id}"></canvas>
        <div class="sig-actions">
          <span class="sig-hint">Sign with your mouse or finger</span>
          <button type="button" class="sig-clear" onclick="clearSig('${f.id}')">Clear</button>
        </div></div>
        <input type="hidden" name="${f.id}" id="sv-${f.id}"/>`; break;
    default: return '';
  }
  const hint=f.hint?`<div class="field-hint">${esc(f.hint)}</div>`:'';
  return`<div class="field ${wCls}" id="field-${f.id}"><label>${esc(f.label)}${req}</label>${inner}${hint}<div class="err" id="err-${f.id}"></div></div>`;
}

function renderForm(){
  buildSteps();
  _curStep=0; _stepData={};
  renderStep();
}

function renderStep(){
  const isMulti=_steps.length>1;
  const step=_steps[_curStep];
  const isLast=_curStep===_steps.length-1;

  const progressHtml=isMulti?`<div class="step-bar">
    ${_steps.map((s,i)=>`
      <div class="sdot ${i<_curStep?'done':i===_curStep?'active':''}">${i<_curStep?'&#x2713;':i+1}</div>
      ${i<_steps.length-1?`<div class="sline ${i<_curStep?'done':''}"></div>`:''}
    `).join('')}
  </div>`:'';

  let fieldsHtml=`<div class="fields-grid">`;
  step.fields.forEach(f=>{fieldsHtml+=renderFieldHtml(f);});
  fieldsHtml+=`</div>`;

  const navHtml=isMulti?`<div class="step-btns">
    ${_curStep>0?`<button type="button" class="step-back" onclick="goStep(-1)">&#8592; Back</button>`:''}
    ${isLast
      ?`<button type="submit" class="btn-submit step-next" id="sub-btn">${esc(FORM.submit_label||'Submit')}</button>`
      :`<button type="button" class="step-next" onclick="goStep(1)">${esc(_steps[_curStep+1].label)} &#8594;</button>`
    }
  </div>`:`<button type="submit" class="btn-submit" id="sub-btn">${esc(FORM.submit_label||'Submit')}</button>`;

  const html=`<div class="form-hdr fade-in">
    <div class="form-hdr-logo"><svg viewBox="0 0 24 24"><rect x="3" y="3" width="18" height="18" rx="2"/><path d="M3 9h18M9 21V9"/></svg></div>
    <h1>${esc(FORM.title)}</h1>${FORM.description&&_curStep===0?`<p>${esc(FORM.description)}</p>`:''}
  </div>
  <div class="form-body fade-in">
  <div class="global-err" id="global-err">
    <svg viewBox="0 0 24 24"><circle cx="12" cy="12" r="10"/><line x1="12" y1="8" x2="12" y2="12"/><line x1="12" y1="16" x2="12.01" y2="16"/></svg>
    <span id="global-err-msg"></span>
  </div>
  <form id="the-form" enctype="multipart/form-data">
    ${progressHtml}${fieldsHtml}${navHtml}
  </form></div>`;

  document.getElementById('card').innerHTML=html;
  initSignatures();
  document.getElementById('the-form').addEventListener('submit', submitForm);
}

function saveCurrentStepData(){
  const step=_steps[_curStep];
  step.fields.forEach(f=>{
    if(f.type==='file'||f.type==='signature'||f.type==='page-break') return;
    if(f.type==='checkbox'){
      _stepData[f.id]=[...document.querySelectorAll(`[name="${f.id}[]"]:checked`)].map(el=>el.value);
    } else {
      const el=document.querySelector(`[name="${f.id}"]`);
      if(el) _stepData[f.id]=el.value;
    }
  });
}

function validateStep(){
  const step=_steps[_curStep];
  let ok=true;
  step.fields.forEach(f=>{
    if(!f.required) return;
    const fieldDiv=document.getElementById('field-'+f.id);
    if(!fieldDiv) return;
    fieldDiv.classList.remove('has-err');
    const errEl=document.getElementById('err-'+f.id);
    if(errEl) errEl.textContent='';
    let val='';
    if(f.type==='checkbox') val=[...document.querySelectorAll(`[name="${f.id}[]"]:checked`)].length?'ok':'';
    else if(f.type==='radio') val=document.querySelector(`[name="${f.id}"]:checked`)?.value||'';
    else if(f.type==='file') val=(fileSelections[f.id]||[]).length?'ok':'';
    else { const el=document.querySelector(`[name="${f.id}"]`); val=el?el.value.trim():'';}
    if(!val){ ok=false; fieldDiv.classList.add('has-err'); if(errEl){errEl.textContent='This field is required';errEl.style.display='block';}}
  });
  return ok;
}

function goStep(dir){
  if(dir>0 && !validateStep()) return;
  saveCurrentStepData();
  _curStep+=dir;
  if(_curStep<0) _curStep=0;
  if(_curStep>=_steps.length) _curStep=_steps.length-1;
  renderStep();
  window.scrollTo({top:0,behavior:'smooth'});
}

function initSignatures(){
  FIELDS.filter(f=>f.type==='signature').forEach(f=>{
    const canvas=document.getElementById('sc-'+f.id);
    if(!canvas) return;
    const pad=new SignaturePad(canvas,{penColor:'#0a1628',backgroundColor:'rgba(0,0,0,0)'});
    pads[f.id]=pad;
    function resize(){
      // Save data before resize so the signature survives layout reflows
      const data = pad.isEmpty() ? null : pad.toDataURL();
      canvas.width=canvas.offsetWidth*window.devicePixelRatio;
      canvas.height=canvas.offsetHeight*window.devicePixelRatio;
      canvas.getContext('2d').scale(window.devicePixelRatio,window.devicePixelRatio);
      pad.clear();
      if(data) pad.fromDataURL(data);
    }
    new ResizeObserver(resize).observe(canvas); resize();
  });
}

function clearSig(id){pads[id]?.clear(); document.getElementById('sv-'+id).value='';}

function handleFiles(id, input, fileList){
  fileSelections[id]=fileSelections[id]||[];
  // Accept either an input element or a FileList directly (drag-drop)
  const files = fileList || (input && input.files);
  if(files) Array.from(files).forEach(f=>fileSelections[id].push(f));
  renderFileList(id);
}

function renderFileList(id){
  const list=document.getElementById('fl-'+id);
  if(!list) return;
  list.innerHTML=(fileSelections[id]||[]).map((f,i)=>`
    <div class="file-item">
      <svg viewBox="0 0 24 24"><path d="M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z"/><polyline points="14 2 14 8 20 8"/></svg>
      <span>${esc(f.name)} <span style="color:#94a3b8">(${(f.size/1024).toFixed(0)}KB)</span></span>
      <button type="button" class="rm" onclick="removeFile('${id}',${i})">✕</button>
    </div>`).join('');
}

function removeFile(id,i){
  // Re-render after splice to keep indices in sync with DOM
  fileSelections[id].splice(i,1);
  renderFileList(id);
}

async function submitForm(e){
  e.preventDefault();
  const btn=document.getElementById('sub-btn');
  btn.disabled=true; btn.innerHTML='<span class="spinner"></span>Submitting…';
  document.getElementById('global-err').className='global-err';

  // Save current step data first
  saveCurrentStepData();

  // Capture signatures (only current step has them in DOM)
  FIELDS.filter(f=>f.type==='signature').forEach(f=>{
    const pad=pads[f.id];
    if(pad&&!pad.isEmpty()) _stepData[f.id]=pad.toDataURL();
  });

  const fd=new FormData();
  if(window._formPW) fd.append('_form_password',window._formPW);

  FIELDS.filter(f=>f.type!=='page-break').forEach(f=>{
    const id=f.id; const type=f.type;
    if(type==='file'){
      (fileSelections[id]||[]).forEach(file=>fd.append(id,file));
    } else if(type==='signature'){
      if(_stepData[id]) fd.append(id,_stepData[id]);
    } else if(type==='checkbox'){
      const vals=_stepData[id]||[];
      vals.forEach(v=>fd.append(id,v));
    } else {
      const val=_stepData[id]||'';
      if(val) fd.append(id,val);
    }
  });

  try{
    const r=await fetch(API+'/submit/'+slug,{method:'POST',body:fd});
    const j=await r.json();
    btn.disabled=false; btn.innerHTML=esc(FORM.submit_label||'Submit');
    if(j.ok){
      if(j.success_url) { window.location.href=j.success_url; return; }
      renderSuccess(j.ref);
    } else {
      const ge=document.getElementById('global-err');
      const msg=document.getElementById('global-err-msg');
      if(msg) msg.textContent=j.error||'Submission failed. Please try again.';
      else ge.textContent=j.error||'Submission failed. Please try again.';
      ge.className='global-err show';
      if(j.errors) {
        const labelToId = Object.fromEntries(FIELDS.map(f=>[f.label, f.id]));
        j.errors.forEach(err=>{
          const label = Object.keys(labelToId).find(k=>err.startsWith(k));
          if(!label) return;
          const fid = labelToId[label];
          const fieldDiv = document.getElementById('field-'+fid);
          if(fieldDiv) {
            fieldDiv.classList.add('has-err');
            const errEl = document.getElementById('err-'+fid);
            if(errEl) { errEl.textContent = err; errEl.style.display='block'; }
          }
        });
      }
    }
  }catch(err){
    btn.disabled=false; btn.innerHTML=esc(FORM.submit_label||'Submit');
    const ge=document.getElementById('global-err');
    const msg=document.getElementById('global-err-msg');
    const txt='Network error. Please check your connection and try again.';
    if(msg) msg.textContent=txt; else ge.textContent=txt;
    ge.className='global-err show';
  }
}

function renderSuccess(ref){
  document.getElementById('card').innerHTML=`
    <div class="form-hdr fade-in">
      <div class="form-hdr-logo"><svg viewBox="0 0 24 24"><rect x="3" y="3" width="18" height="18" rx="2"/><path d="M3 9h18M9 21V9"/></svg></div>
      <h1>${esc(FORM.title)}</h1>
    </div>
    <div class="success-box fade-in">
      <div class="success-icon"><svg viewBox="0 0 24 24"><polyline points="20 6 9 17 4 12"/></svg></div>
      <h2>Submitted Successfully!</h2>
      <p>Thank you — your response has been recorded.</p>
      <p>A confirmation has been sent to your email.</p>
      <div class="success-ref">
        <svg width="12" height="12" viewBox="0 0 24 24" style="stroke:currentColor;fill:none;stroke-width:2;stroke-linecap:round"><path d="M9 12l2 2 4-4"/><circle cx="12" cy="12" r="10"/></svg>
        Ref: ${esc(ref)}
      </div>
      <button onclick="location.reload()" style="margin-top:22px;padding:11px 26px;background:var(--ac);color:#fff;border:none;border-radius:var(--r10);font-size:14px;font-weight:500;cursor:pointer;font-family:var(--font);transition:background .15s" onmouseover="this.style.background='var(--ac-dark)'" onmouseout="this.style.background='var(--ac)'">Submit Another Response</button>
    </div>`;
}

loadForm();
</script>
</body>
</html>
