let allWaiverRows = [];
let waiverWalks = [];

function waiverEsc(value) {
  return Pyrk.esc(value ?? '');
}

function waiverFormatDate(value) {
  return value ? Pyrk.formatDate(value) : '—';
}

function waiverFormatDateTime(value) {
  return value ? Pyrk.formatDateTime(value) : '—';
}

function waiverStatusPill(text, tone = 'green') {
  const cls = tone === 'green' ? 'pill-green' : tone === 'red' ? 'pill-red' : 'pill-muted';
  return `<span class="pill ${cls}">${waiverEsc(text)}</span>`;
}

function waiverMemberLine(w) {
  return `<div class="waiver-member-cell">
    <strong>${waiverEsc(w.member_name || 'Member')}</strong>
    <small>${waiverEsc(w.member_email || '')}</small>
    <small>${waiverEsc(w.member_mobile || '')}</small>
  </div>`;
}

function waiverWalkLine(w) {
  return `<div class="waiver-walk-cell">
    <strong>${waiverEsc(w.walk_title || 'Walk')}</strong>
    <small>${waiverFormatDate(w.walk_date)} ${w.start_time ? '· ' + waiverEsc(String(w.start_time).slice(0, 5)) : ''}</small>
    <small>${waiverEsc(w.route_name || '')}${w.total_km ? ' · ' + Number(w.total_km).toFixed(1) + ' KM' : ''}</small>
  </div>`;
}

function renderWaiverRows(rows) {
  const body = document.getElementById('waiversTableBody');
  if (!body) return;

  if (!rows || !rows.length) {
    body.innerHTML = '<tr><td colspan="6"><div class="empty-state-pro"><strong>No signed waivers found.</strong><span>Try another walk filter or search keyword.</span></div></td></tr>';
    return;
  }

  body.innerHTML = rows.map(w => `<tr>
    <td>${waiverMemberLine(w)}</td>
    <td>${waiverWalkLine(w)}</td>
    <td><strong>${waiverEsc(w.signed_name || '—')}</strong><small>${waiverEsc(w.waiver_title || 'Waiver')} v${Number(w.waiver_version || 1)}</small></td>
    <td><strong>${waiverFormatDateTime(w.signed_at)}</strong>${waiverStatusPill('Signed', 'green')}</td>
    <td><small>${waiverEsc(w.ip_address || 'No IP')}</small><small>${waiverEsc(String(w.device_info || 'No device').slice(0, 80))}</small></td>
    <td>
      <div class="inline-controls tiny-controls waiver-row-actions">
        <button class="btn btn-small" type="button" onclick="openWaiverDetail(${Number(w.id)})">View</button>
        <button class="btn btn-light btn-small" type="button" onclick="printWaiver(${Number(w.id)})">Print</button>
      </div>
    </td>
  </tr>`).join('');
}

async function loadWaiverStats() {
  const res = await Pyrk.get('admin_waivers.php', {action: 'stats'});
  if (!res.ok) return;
  const s = res.data?.stats || {};
  const set = (id, value) => { const el = document.getElementById(id); if (el) el.textContent = Number(value || 0).toLocaleString(); };
  set('waiverTotal', s.total);
  set('waiverToday', s.today);
  set('waiverWalks', s.walks);
  set('waiverMembers', s.members);
}

async function loadWaiverWalks() {
  const select = document.getElementById('waiverWalkFilter');
  if (!select) return;
  const res = await Pyrk.get('admin_waivers.php', {action: 'walks'});
  if (!res.ok) return;
  waiverWalks = res.data?.walks || [];
  const current = select.value || String(window.PYRK_WAIVER_WALK_ID || '');
  select.innerHTML = '<option value="">All walks</option>' + waiverWalks.map(w => {
    const label = `${w.title || 'Walk'} · ${waiverFormatDate(w.walk_date)}${w.route_name ? ' · ' + w.route_name : ''} (${Number(w.signed_count || 0)} signed)`;
    return `<option value="${Number(w.id)}">${waiverEsc(label)}</option>`;
  }).join('');
  if (current) select.value = current;
}

async function loadWaivers() {
  const body = document.getElementById('waiversTableBody');
  if (body) body.innerHTML = '<tr><td colspan="6" class="muted">Loading signed waivers...</td></tr>';

  const params = {
    action: 'list',
    q: document.getElementById('waiverSearch')?.value || '',
    walk_id: document.getElementById('waiverWalkFilter')?.value || window.PYRK_WAIVER_WALK_ID || '',
    user_id: window.PYRK_WAIVER_MEMBER_ID || '',
    limit: 250
  };
  const res = await Pyrk.get('admin_waivers.php', params);
  if (!res.ok) {
    if (body) body.innerHTML = `<tr><td colspan="6"><div class="notice bad">${waiverEsc(res.message || 'Could not load signed waivers.')}</div></td></tr>`;
    return;
  }
  allWaiverRows = res.data?.waivers || [];
  renderWaiverRows(allWaiverRows);
}

function waiverPrintHtml(w) {
  const signature = w.signature_data ? `<div class="print-signature"><img src="${waiverEsc(w.signature_data)}" alt="Digital signature"></div>` : '<div class="print-signature-empty">No drawn signature saved.</div>';
  return `<!doctype html><html><head><meta charset="utf-8"><title>Signed waiver #${Number(w.id)}</title>
  <style>
    body{font-family:Arial,sans-serif;color:#111827;margin:0;background:#f6f7fb;padding:28px}.page{max-width:880px;margin:auto;background:#fff;border:1px solid #e5e7eb;border-radius:24px;padding:34px;box-shadow:0 20px 60px rgba(15,23,42,.08)}
    h1{margin:0 0 6px;font-size:28px}.muted{color:#667085}.grid{display:grid;grid-template-columns:1fr 1fr;gap:12px;margin:22px 0}.field{border:1px solid #e5e7eb;border-radius:14px;padding:12px;background:#fafafa}.field span{display:block;font-size:11px;text-transform:uppercase;letter-spacing:.08em;color:#667085;font-weight:800}.field strong{display:block;margin-top:4px}.waiver-body{border:1px solid #e5e7eb;border-radius:18px;padding:18px;margin:20px 0;line-height:1.55}.print-signature{border:1px solid #d1d5db;border-radius:16px;padding:18px;margin-top:10px;min-height:120px}.print-signature img{max-width:100%;max-height:180px}.print-signature-empty{border:1px dashed #d1d5db;border-radius:16px;padding:24px;color:#667085}.footer{margin-top:22px;font-size:12px;color:#667085}@media print{body{background:#fff;padding:0}.page{box-shadow:none;border:0;border-radius:0}.no-print{display:none}}
  </style></head><body><div class="page">
    <h1>Signed Waiver</h1><p class="muted">Audit copy generated from Pyrk Admin.</p>
    <div class="grid">
      <div class="field"><span>Member</span><strong>${waiverEsc(w.member_name || '')}</strong><small>${waiverEsc(w.member_email || '')}</small></div>
      <div class="field"><span>Walk</span><strong>${waiverEsc(w.walk_title || '')}</strong><small>${waiverFormatDate(w.walk_date)} ${w.start_time ? waiverEsc(String(w.start_time).slice(0,5)) : ''}</small></div>
      <div class="field"><span>Signed as</span><strong>${waiverEsc(w.signed_name || '')}</strong></div>
      <div class="field"><span>Signed at</span><strong>${waiverFormatDateTime(w.signed_at)}</strong></div>
      <div class="field"><span>IP address</span><strong>${waiverEsc(w.ip_address || '—')}</strong></div>
      <div class="field"><span>Device</span><strong>${waiverEsc(w.device_info || '—')}</strong></div>
    </div>
    <h2>${waiverEsc(w.waiver_title || 'Waiver terms')} v${Number(w.waiver_version || 1)}</h2>
    <div class="waiver-body">${w.waiver_body_html || ''}</div>
    <h2>Digital signature</h2>${signature}
    <p class="footer">Waiver record #${Number(w.id)} · Accepted terms: ${Number(w.accepted_terms || 0) === 1 ? 'Yes' : 'No'}</p>
    <button class="no-print" onclick="window.print()">Print</button>
  </div></body></html>`;
}

function renderWaiverDetail(w) {
  const signature = w.signature_data ? `<div class="waiver-signature-preview"><img src="${waiverEsc(w.signature_data)}" alt="Digital signature"></div>` : '<div class="waiver-signature-preview is-empty">No drawn signature saved.</div>';
  return `<div class="signed-waiver-document" data-waiver-id="${Number(w.id)}">
    <section class="waiver-detail-hero-card">
      <div>
        <p class="eyebrow">Accepted and signed</p>
        <h3>${waiverEsc(w.member_name || 'Member')}</h3>
        <p class="muted">${waiverEsc(w.member_email || '')} · ${waiverEsc(w.member_mobile || 'No mobile')}</p>
      </div>
      <div class="waiver-detail-actions">
        ${waiverStatusPill('Signed', 'green')}
        <button class="btn btn-small" type="button" onclick="printWaiver(${Number(w.id)})">Print waiver</button>
      </div>
    </section>

    <section class="waiver-detail-grid">
      <div class="waiver-detail-field"><span>Walk</span><strong>${waiverEsc(w.walk_title || '—')}</strong><small>${waiverFormatDate(w.walk_date)} ${w.start_time ? '· ' + waiverEsc(String(w.start_time).slice(0, 5)) : ''}</small></div>
      <div class="waiver-detail-field"><span>Route</span><strong>${waiverEsc(w.route_name || '—')}</strong><small>${w.total_km ? Number(w.total_km).toFixed(1) + ' KM' : ''}</small></div>
      <div class="waiver-detail-field"><span>Signed name</span><strong>${waiverEsc(w.signed_name || '—')}</strong></div>
      <div class="waiver-detail-field"><span>Signed at</span><strong>${waiverFormatDateTime(w.signed_at)}</strong></div>
      <div class="waiver-detail-field"><span>IP address</span><strong>${waiverEsc(w.ip_address || '—')}</strong></div>
      <div class="waiver-detail-field"><span>Device</span><strong>${waiverEsc(String(w.device_info || '—').slice(0, 160))}</strong></div>
    </section>

    <section class="waiver-terms-preview">
      <div class="mini-section-head"><div><p class="eyebrow">Template</p><h3>${waiverEsc(w.waiver_title || 'Waiver terms')} <span>v${Number(w.waiver_version || 1)}</span></h3></div></div>
      <div class="waiver-body-box">${w.waiver_body_html || '<p>No waiver terms found.</p>'}</div>
    </section>

    <section class="waiver-signature-card">
      <div class="mini-section-head"><div><p class="eyebrow">Proof</p><h3>Digital signature</h3></div></div>
      ${signature}
    </section>
  </div>`;
}

window.openWaiverDetail = async function openWaiverDetail(id) {
  const modal = document.getElementById('waiverDetailModal');
  const content = document.getElementById('waiverDetailContent');
  if (content) content.innerHTML = '<p class="muted">Loading signed waiver...</p>';
  Pyrk.openModal(modal);
  const res = await Pyrk.get('admin_waivers.php', {action: 'detail', id});
  if (!res.ok) {
    if (content) content.innerHTML = `<div class="notice bad">${waiverEsc(res.message || 'Could not load signed waiver.')}</div>`;
    return;
  }
  const w = res.data?.waiver || {};
  document.getElementById('waiverDetailTitle').textContent = `Waiver #${Number(w.id || id)}`;
  if (content) content.innerHTML = renderWaiverDetail(w);
};

window.printWaiver = async function printWaiver(id) {
  const res = await Pyrk.get('admin_waivers.php', {action: 'detail', id});
  if (!res.ok) { alert(res.message || 'Could not load waiver.'); return; }
  const w = res.data?.waiver || {};
  const win = window.open('', '_blank', 'noopener,width=920,height=900');
  if (!win) { alert('Popup blocked. Please allow popups to print the waiver.'); return; }
  win.document.open();
  win.document.write(waiverPrintHtml(w));
  win.document.close();
  setTimeout(() => { try { win.focus(); win.print(); } catch (e) {} }, 400);
};

function installWaiverListeners() {
  document.getElementById('waiverRefreshBtn')?.addEventListener('click', loadWaivers);
  document.getElementById('waiverWalkFilter')?.addEventListener('change', loadWaivers);
  let timer = null;
  document.getElementById('waiverSearch')?.addEventListener('input', () => {
    clearTimeout(timer);
    timer = setTimeout(loadWaivers, 250);
  });

  if (window.PYRK_WAIVER_WALK_ID) {
    const select = document.getElementById('waiverWalkFilter');
    if (select) select.value = String(window.PYRK_WAIVER_WALK_ID);
  }
}

(async function initWaiversPage() {
  installWaiverListeners();
  await Promise.all([loadWaiverStats(), loadWaiverWalks()]);
  await loadWaivers();
  if (window.PYRK_WAIVER_OPEN_ID) {
    openWaiverDetail(window.PYRK_WAIVER_OPEN_ID);
  }
})();
