/**
 * Uploader (user) workflow: when they can open the printable HTML summary.
 * ORAC uses assessment_status_id 2 = Complete (see executor getAssignmentStatusDisplayLabel).
 */

export function isUserUploadStatusComplete(row) {
  const id = Number(row?.assessment_status_id);
  if (id === 2) return true;
  const n = String(row?.assessment_status_name || '').toLowerCase();
  return n.includes('complete') || n.includes('done');
}

export function isUserUploadStatusInProgress(row) {
  const label = String(row?.assessment_status_name || '').toLowerCase();
  return label.includes('progress') || label.includes('ongoing');
}

/** Verifier-style Risk Reduction Plan (same UI as verifier Generate Report) — only after completion. */
export function canUserDownloadVerifierRiskReport(row) {
  return isUserUploadStatusComplete(row);
}

/** Short printable summary (metadata only) while work is still in progress. */
export function canUserDownloadQuickSummaryReport(row) {
  if (isUserUploadStatusComplete(row)) return false;
  return isUserUploadStatusInProgress(row);
}

/** Show a Download action: full verifier report when complete, or quick summary when in progress. */
export function canUserDownloadAssessmentReport(row) {
  return canUserDownloadVerifierRiskReport(row) || canUserDownloadQuickSummaryReport(row);
}

function escapeHtml(value) {
  return String(value || '--')
    .replaceAll('&', '&amp;')
    .replaceAll('<', '&lt;')
    .replaceAll('>', '&gt;')
    .replaceAll('"', '&quot;')
    .replaceAll("'", '&#39;');
}

function formatDateForReport(val) {
  if (!val) return '--';
  try {
    const d = new Date(val);
    return d.toLocaleDateString('en-IN', { day: '2-digit', month: 'short', year: 'numeric' });
  } catch {
    return String(val);
  }
}

function statusLabelForReport(row) {
  return row?.assessment_status_name || `Status ${row?.assessment_status_id ?? '—'}`;
}

/**
 * Opens a print-friendly HTML summary (user can print to PDF from the browser).
 * Uses a blob URL so the report loads reliably: `window.open(..., 'noopener')` returns null
 * in modern browsers, so `document.write` on the opener never runs and the tab stays blank.
 */
export function openUserAssessmentReport(row) {
  const v = row;
  const rows = [
    ['Assessment ID', v.assessment_id],
    ['Video Title', v.video_title],
    ['Location', v.location_name],
    ['Work Area', v.department_name],
    ['Contract Details', v.contract_details ?? v.contact_details],
    ['Capture Date', formatDateForReport(v.video_capture_date)],
    ['Capture Time', v.video_capture_time],
    ['Status', statusLabelForReport(v)],
    ['Remarks', v.remarks]
  ];
  const reportHtml = `<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8" />
  <title>Risk Assessment Report - ${escapeHtml(v.video_title || v.assessment_id)}</title>
  <style>
    body { font-family: Arial, sans-serif; margin: 28px; color: #111827; }
    h1 { margin: 0 0 8px; font-size: 24px; }
    p { margin: 0 0 20px; color: #4b5563; }
    table { border-collapse: collapse; width: 100%; }
    td { border: 1px solid #d1d5db; padding: 10px; vertical-align: top; }
    td:first-child { width: 30%; font-weight: 700; background: #f9fafb; }
  </style>
</head>
<body>
  <h1>Risk Assessment Report</h1>
  <p>Generated on ${escapeHtml(new Date().toLocaleString('en-IN'))}</p>
  <table>
    ${rows
      .map(([label, value]) => `<tr><td>${escapeHtml(label)}</td><td>${escapeHtml(value)}</td></tr>`)
      .join('')}
  </table>
  <script>
    window.addEventListener('load', function () { window.print(); });
  <\/script>
</body>
</html>`;

  const blob = new Blob([reportHtml], { type: 'text/html;charset=utf-8' });
  const url = URL.createObjectURL(blob);
  const win = window.open(url, '_blank', 'noopener,noreferrer');
  if (!win) {
    URL.revokeObjectURL(url);
    window.alert('Please allow popups to download or print the report.');
    return;
  }
  const revoke = () => {
    try {
      URL.revokeObjectURL(url);
    } catch {
      /* ignore */
    }
  };
  win.addEventListener('load', () => setTimeout(revoke, 250));
  win.addEventListener('pagehide', revoke);
}
