'use client';

import React from 'react';
import type {
  MyAuditRow,
  AuditRequestSnapshot,
} from '@/lib/api/types/my-audits.types';
import { AUDIT_REQUESTS_API_BASE_URL } from '@/lib/api/audit-request.api';

const FILE_ORIGIN = AUDIT_REQUESTS_API_BASE_URL.replace(/\/api\/?$/, '');

interface Props {
  row: MyAuditRow;
  auditRequest: AuditRequestSnapshot | null;
}

// ─────────────────────────────────────────────────────────────────────────
// Auditee shape — comes from audit_requests.auditees (parsed array) via the
// workspace endpoint. Falls back to the single auditee_name string for old
// requests that pre-date the multi-auditee feature.
// ─────────────────────────────────────────────────────────────────────────
type Auditee = { name?: string; designation?: string; position?: string; email?: string };

function resolveAuditees(
  auditRequest: AuditRequestSnapshot | null,
  fallbackContact?: string | null,
  fallbackEmail?: string | null,
): Array<{ name: string; designation: string; email: string }> {
  const raw = (auditRequest as any)?.auditees;
  let list: Auditee[] = [];

  if (Array.isArray(raw)) {
    list = raw;
  } else if (typeof raw === 'string' && raw.trim()) {
    try {
      const parsed = JSON.parse(raw);
      if (Array.isArray(parsed)) list = parsed;
    } catch {
      /* ignore — fall through to legacy single name */
    }
  }

  const cleaned = list
    .map((a) => ({
      name: String(a?.name ?? '').trim(),
      designation: String(a?.designation ?? a?.position ?? '').trim(),
      email: String(a?.email ?? '').trim(),
    }))
    .filter((a) => a.name);

  if (cleaned.length) {
    // No per-auditee email is stored in the auditees JSON, so if none of them
    // have one, put the request-level email on the first attendee.
    const anyEmail = cleaned.some((a) => a.email);
    if (!anyEmail && fallbackEmail) {
      cleaned[0] = { ...cleaned[0], email: String(fallbackEmail).trim() };
    }
    return cleaned;
  }

  // Legacy single auditee — split "Name - Designation" if present.
  const single = (auditRequest?.auditee_name || fallbackContact || '').trim();
  if (!single) return [];
  if (single.includes(' - ')) {
    const [name, ...rest] = single.split(' - ');
    return [{ name: name.trim(), designation: rest.join(' - ').trim(), email: String(fallbackEmail ?? '').trim() }];
  }
  return [{ name: single, designation: '', email: String(fallbackEmail ?? '').trim() }];
}

export default function DetailsTab({ row, auditRequest }: Props) {
  const standards = (row.standards ?? []).map((s) => s.name).join(', ') || '—';
  const auditees = resolveAuditees(
    auditRequest,
    row.company?.contact_person,
    auditRequest?.auditee_email || row.company?.email || '',
  );

  const coordinatorName = row.schedule?.coordinator
    ? `${row.schedule.coordinator.firstName ?? ''} ${
        row.schedule.coordinator.lastName ?? ''
      }`.trim()
    : '';

  const scheduleDate = row.schedule?.schedule_date || '';
  const dateTime = [scheduleDate, row.audit_time_label ? `· ${row.audit_time_label}` : '']
    .filter(Boolean)
    .join(' ');
  const auditCode = (row as any).audit_code || '';

  // ── Print to PDF — opens a clean, branded print window of just the details ──
  const handlePrint = () => {
    const win = window.open('', '_blank', 'width=900,height=1000');
    if (!win) return;
    win.document.write(
      buildPrintHtml({
        companyName: row.company?.name || '—',
        companyCode: row.company?.company_code || '—',
        auditCode: auditCode || '—',
        auditees,
        contact: auditRequest?.auditee_contact || row.company?.mobile || '—',
        email: auditRequest?.auditee_email || row.company?.email || '—',
        location: auditRequest?.location || row.company?.city || '—',
        auditType: row.audit_type || '—',
        auditStage: row.audit_stage || '—',
        auditMode: row.audit_mode || '—',
        standards,
        accreditation: row.accreditation || '—',
        dateTime: dateTime || '—',
        coordinator: coordinatorName || '—',
        marketingRemarks: auditRequest?.marketing_remarks || '',
        coordinatorRemarks: auditRequest?.coordinator_remarks || '',
        notes: row.notes || '',
      }),
    );
    win.document.close();
    win.focus();
    setTimeout(() => win.print(), 350);
  };

  return (
    <div className="dt-root">
      <style>{CSS}</style>

      {/* ── Hero / dossier header ── */}
      <header className="dt-hero">
        <div className="dt-hero-rule" />
        <div className="dt-hero-inner">
          <div className="dt-hero-left">
            <span className="dt-eyebrow">Audit</span>
            <h2 className="dt-hero-title">{row.company?.name || 'Audit'}</h2>
            <div className="dt-hero-meta">
              {auditCode && <span className="dt-code">{auditCode}</span>}
              {dateTime && <span className="dt-dot" />}
              {dateTime && <span>{dateTime}</span>}
            </div>
          </div>
          <button className="dt-print" onClick={handlePrint} title="Print these details as PDF">
            <PrinterIcon />
            <span>Print PDF</span>
          </button>
        </div>
      </header>

      {/* ── Key facts strip ── */}
      <div className="dt-facts">
        <Fact label="Type" value={row.audit_type} />
        <Fact label="Stage" value={row.audit_stage} />
        <Fact label="Mode" value={row.audit_mode} />
        <Fact label="Schedule" value={scheduleDate || '—'} />
      </div>

      {/* ── Spec cards ── */}
      <div className="dt-grid">
        <Card title="Client" accent="#7c3aed">
          <Row label="Company" value={row.company?.name} strong />
          <Row label="Company code" value={row.company?.company_code} mono />
          <Row label="Contact" value={auditRequest?.auditee_contact || row.company?.mobile} />
          <Row label="Email" value={auditRequest?.auditee_email || row.company?.email} />
          <Row label="Location" value={auditRequest?.location || row.company?.city} />
        </Card>

        <Card title="Audit scope" accent="#0d9488">
          <Row label="Standards" value={standards} />
          <Row label="Accreditation" value={row.accreditation} />
          <Row label="Date & time" value={dateTime || '—'} />
          <Row label="Coordinator" value={coordinatorName || '—'} />
        </Card>
      </div>

      {/* ── Auditees / Attendees ── */}
      <Card
        title="Auditees / Attendees"
        accent="#b45309"
        full
        count={auditees.length || undefined}
      >
        {auditees.length === 0 ? (
          <div className="dt-empty">No auditees recorded on the audit request.</div>
        ) : (
          <div className="dt-aud-list">
            {auditees.map((a, i) => (
              <div className="dt-aud-row" key={i}>
                <span className="dt-aud-idx">{String(i + 1).padStart(2, '0')}</span>
                <span className="dt-aud-avatar">{initials(a.name)}</span>
                <span className="dt-aud-main">
                  <span className="dt-aud-name">{a.name}</span>
                  <span className="dt-aud-desig">
                    {a.designation || 'Designation not specified'}
                  </span>
                  {a.email && (
                    <a className="dt-aud-email" href={`mailto:${a.email}`}>
                      {a.email}
                    </a>
                  )}
                </span>
              </div>
            ))}
          </div>
        )}
      </Card>

      {/* ── Attachment pack ── */}
      {Array.isArray(auditRequest?.documents) && auditRequest!.documents!.length > 0 && (
        <Card
          title="Audit attachment pack"
          accent="#4338ca"
          full
          count={auditRequest!.documents!.length}
        >
          <div className="dt-file-list">
            {auditRequest!.documents!.map((d, i) => (
              <a
                key={i}
                className="dt-file"
                href={`${FILE_ORIGIN}/${d.path}`}
                target="_blank"
                rel="noopener noreferrer"
              >
                <span className="dt-file-icon">
                  <FileIcon />
                </span>
                <span className="dt-file-name">{d.filename}</span>
                <span className="dt-file-size">{(d.size / 1024).toFixed(0)} KB</span>
              </a>
            ))}
          </div>
        </Card>
      )}

      {/* ── Remarks ── */}
      {auditRequest?.marketing_remarks && (
        <Callout label="Marketing remarks" color="#7c3aed" text={auditRequest.marketing_remarks} />
      )}
      {auditRequest?.coordinator_remarks && (
        <Callout label="Coordinator notes" color="#15803d" text={auditRequest.coordinator_remarks} />
      )}
      {row.notes && <Callout label="Audit notes" color="#b45309" text={row.notes} />}
    </div>
  );
}

// ═══════════════════════════════════════════════════════════════════════
// Sub-components
// ═══════════════════════════════════════════════════════════════════════

function Fact({ label, value }: { label: string; value?: React.ReactNode }) {
  return (
    <div className="dt-fact">
      <span className="dt-fact-label">{label}</span>
      <span className="dt-fact-value">{value || '—'}</span>
    </div>
  );
}

function Card({
  title,
  accent,
  full,
  count,
  children,
}: {
  title: string;
  accent: string;
  full?: boolean;
  count?: number;
  children: React.ReactNode;
}) {
  return (
    <section
      className={`dt-card${full ? ' dt-card-full' : ''}`}
      style={{ ['--accent' as any]: accent }}
    >
      <div className="dt-card-head">
        <span className="dt-card-bar" />
        <h3 className="dt-card-title">{title}</h3>
        {count != null && <span className="dt-card-count">{count}</span>}
      </div>
      <div className="dt-card-body">{children}</div>
    </section>
  );
}

function Row({
  label,
  value,
  strong,
  mono,
}: {
  label: string;
  value?: React.ReactNode;
  strong?: boolean;
  mono?: boolean;
}) {
  return (
    <div className="dt-row">
      <span className="dt-row-label">{label}</span>
      <span className={`dt-row-value${strong ? ' is-strong' : ''}${mono ? ' is-mono' : ''}`}>
        {value ?? '—'}
      </span>
    </div>
  );
}

function Callout({ label, color, text }: { label: string; color: string; text: string }) {
  return (
    <div className="dt-callout" style={{ ['--c' as any]: color }}>
      <span className="dt-callout-label">{label}</span>
      <p className="dt-callout-text">{text}</p>
    </div>
  );
}

function PrinterIcon() {
  return (
    <svg width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor"
      strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
      <polyline points="6 9 6 2 18 2 18 9" />
      <path d="M6 18H4a2 2 0 0 1-2-2v-5a2 2 0 0 1 2-2h16a2 2 0 0 1 2 2v5a2 2 0 0 1-2 2h-2" />
      <rect x="6" y="14" width="12" height="8" />
    </svg>
  );
}

function FileIcon() {
  return (
    <svg width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor"
      strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
      <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>
  );
}

function initials(name: string): string {
  const parts = name.replace(/^(mr|ms|mrs|dr|eng)\.?\s+/i, '').trim().split(/\s+/);
  const a = parts[0]?.[0] ?? '';
  const b = parts.length > 1 ? parts[parts.length - 1][0] : '';
  return (a + b).toUpperCase() || '?';
}

// ═══════════════════════════════════════════════════════════════════════
// Scoped styles — hover, focus, responsive, reduced-motion all handled here.
// ═══════════════════════════════════════════════════════════════════════

const CSS = `
.dt-root {
  --ink: #160a33;
  --ink-2: #2a0f57;
  --line: #ece8f4;
  --line-2: #f3f0fa;
  --muted: #79728f;
  --text: #211a3a;
  --surface: #ffffff;
  display: flex;
  flex-direction: column;
  gap: 16px;
  color: var(--text);
  font-variant-numeric: tabular-nums;
}
.dt-root *,
.dt-root *::before,
.dt-root *::after { box-sizing: border-box; }

/* ── Hero ── */
.dt-hero {
  position: relative;
  overflow: hidden;
  border-radius: 18px;
  background:
    radial-gradient(120% 160% at 100% 0%, rgba(124,58,237,0.45) 0%, rgba(124,58,237,0) 55%),
    linear-gradient(135deg, var(--ink) 0%, var(--ink-2) 100%);
  color: #fff;
  box-shadow: 0 10px 30px -12px rgba(22,10,51,0.55);
}
.dt-hero-rule {
  height: 3px;
  background: linear-gradient(90deg, #d4a017 0%, #f0c14b 40%, rgba(240,193,75,0) 100%);
}
.dt-hero-inner {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  gap: 16px;
  padding: 22px 24px;
  flex-wrap: wrap;
}
.dt-eyebrow {
  display: inline-block;
  font-size: 10px;
  font-weight: 700;
  letter-spacing: 0.18em;
  text-transform: uppercase;
  color: rgba(255,255,255,0.55);
  margin-bottom: 8px;
}
.dt-hero-title {
  margin: 0;
  font-size: 22px;
  line-height: 1.15;
  font-weight: 750;
  letter-spacing: -0.02em;
}
.dt-hero-meta {
  margin-top: 10px;
  display: flex;
  align-items: center;
  gap: 9px;
  font-size: 12.5px;
  color: rgba(255,255,255,0.72);
}
.dt-code {
  font-family: 'JetBrains Mono', ui-monospace, 'Courier New', monospace;
  font-size: 11.5px;
  font-weight: 600;
  letter-spacing: 0.02em;
  color: #f0e9ff;
  background: rgba(255,255,255,0.10);
  border: 1px solid rgba(255,255,255,0.18);
  padding: 3px 9px;
  border-radius: 7px;
}
.dt-dot { width: 3px; height: 3px; border-radius: 50%; background: rgba(255,255,255,0.4); }

.dt-print {
  display: inline-flex;
  align-items: center;
  gap: 8px;
  background: #fff;
  color: var(--ink);
  border: none;
  border-radius: 10px;
  padding: 10px 16px;
  font-size: 12.5px;
  font-weight: 700;
  letter-spacing: 0.01em;
  cursor: pointer;
  transition: transform 0.15s ease, box-shadow 0.15s ease;
  box-shadow: 0 4px 14px -4px rgba(0,0,0,0.4);
}
.dt-print:hover { transform: translateY(-1px); box-shadow: 0 8px 20px -6px rgba(0,0,0,0.45); }
.dt-print:focus-visible { outline: 2px solid #f0c14b; outline-offset: 2px; }

/* ── Key facts ── */
.dt-facts {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(150px, 1fr));
  gap: 10px;
}
.dt-fact {
  background: var(--surface);
  border: 1px solid var(--line);
  border-radius: 12px;
  padding: 12px 14px;
  display: flex;
  flex-direction: column;
  gap: 3px;
}
.dt-fact-label {
  font-size: 9.5px;
  font-weight: 700;
  letter-spacing: 0.1em;
  text-transform: uppercase;
  color: var(--muted);
}
.dt-fact-value {
  font-size: 14px;
  font-weight: 650;
  color: var(--text);
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

/* ── Grid + cards ── */
.dt-grid {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 14px;
}
.dt-card {
  background: var(--surface);
  border: 1px solid var(--line);
  border-radius: 16px;
  padding: 4px 18px 14px;
  transition: box-shadow 0.18s ease, transform 0.18s ease;
}
.dt-card:hover { box-shadow: 0 12px 28px -18px rgba(22,10,51,0.4); }
.dt-card-full { grid-column: 1 / -1; }
.dt-card-head {
  display: flex;
  align-items: center;
  gap: 10px;
  padding: 14px 0 12px;
  border-bottom: 1px solid var(--line-2);
}
.dt-card-bar {
  width: 4px;
  height: 16px;
  border-radius: 3px;
  background: var(--accent);
  flex-shrink: 0;
}
.dt-card-title {
  margin: 0;
  font-size: 11.5px;
  font-weight: 700;
  letter-spacing: 0.07em;
  text-transform: uppercase;
  color: #4b4463;
}
.dt-card-count {
  margin-left: auto;
  min-width: 22px;
  height: 22px;
  padding: 0 7px;
  display: inline-flex;
  align-items: center;
  justify-content: center;
  font-size: 11px;
  font-weight: 700;
  color: var(--accent);
  background: color-mix(in srgb, var(--accent) 12%, white);
  border-radius: 999px;
}
.dt-card-body { padding-top: 4px; }

/* ── Spec rows ── */
.dt-row {
  display: flex;
  align-items: baseline;
  gap: 16px;
  padding: 9px 0;
  border-bottom: 1px solid var(--line-2);
}
.dt-row:last-child { border-bottom: none; }
.dt-row-label {
  flex: 0 0 38%;
  font-size: 12px;
  color: var(--muted);
}
.dt-row-value {
  flex: 1;
  font-size: 13px;
  font-weight: 550;
  color: var(--text);
  word-break: break-word;
}
.dt-row-value.is-strong { font-weight: 700; }
.dt-row-value.is-mono {
  font-family: 'JetBrains Mono', ui-monospace, monospace;
  font-size: 12px;
  letter-spacing: 0.01em;
}

/* ── Auditees ── */
.dt-aud-list { display: flex; flex-direction: column; gap: 8px; padding-top: 8px; }
.dt-aud-row {
  display: flex;
  align-items: center;
  gap: 12px;
  padding: 10px 12px;
  border: 1px solid var(--line);
  border-radius: 12px;
  background: #fcfbfe;
  transition: background 0.15s ease, border-color 0.15s ease;
}
.dt-aud-row:hover { background: #f7f4fd; border-color: #e4ddf5; }
.dt-aud-idx {
  font-size: 11px;
  font-weight: 700;
  color: #b8b1cc;
  font-family: 'JetBrains Mono', ui-monospace, monospace;
  width: 20px;
  flex-shrink: 0;
}
.dt-aud-avatar {
  width: 36px;
  height: 36px;
  border-radius: 10px;
  display: inline-flex;
  align-items: center;
  justify-content: center;
  font-size: 12px;
  font-weight: 700;
  letter-spacing: 0.02em;
  color: #fff;
  flex-shrink: 0;
  background: linear-gradient(135deg, #6d28d9 0%, #9333ea 100%);
  box-shadow: 0 3px 8px -3px rgba(109,40,217,0.55);
}
.dt-aud-main { display: flex; flex-direction: column; min-width: 0; flex: 1; gap: 1px; }
.dt-aud-name {
  font-size: 13.5px;
  font-weight: 700;
  color: var(--text);
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}
.dt-aud-desig { font-size: 11.5px; color: var(--muted); }
.dt-aud-email {
  font-size: 11.5px;
  color: #6d28d9;
  text-decoration: none;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}
.dt-aud-email:hover { text-decoration: underline; }
.dt-empty { font-size: 12.5px; color: #a39bb8; padding: 10px 2px; }

/* ── Files ── */
.dt-file-list { display: flex; flex-direction: column; gap: 8px; padding-top: 8px; }
.dt-file {
  display: flex;
  align-items: center;
  gap: 11px;
  padding: 10px 12px;
  border: 1px solid var(--line);
  border-radius: 12px;
  background: #fcfbfe;
  text-decoration: none;
  transition: background 0.15s ease, border-color 0.15s ease;
}
.dt-file:hover { background: #f3f0fb; border-color: #ddd5f2; }
.dt-file:focus-visible { outline: 2px solid #7c3aed; outline-offset: 2px; }
.dt-file-icon {
  width: 30px; height: 30px;
  display: inline-flex; align-items: center; justify-content: center;
  border-radius: 8px; color: #6d28d9;
  background: #efeafd; flex-shrink: 0;
}
.dt-file-name {
  flex: 1;
  font-size: 13px;
  font-weight: 600;
  color: #5b21b6;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}
.dt-file-size { font-size: 11px; color: #a39bb8; flex-shrink: 0; }

/* ── Callouts ── */
.dt-callout {
  position: relative;
  background: color-mix(in srgb, var(--c) 7%, white);
  border: 1px solid color-mix(in srgb, var(--c) 18%, white);
  border-left: 4px solid var(--c);
  border-radius: 0 12px 12px 0;
  padding: 12px 16px;
}
.dt-callout-label {
  display: block;
  font-size: 9.5px;
  font-weight: 700;
  letter-spacing: 0.07em;
  text-transform: uppercase;
  color: var(--c);
  margin-bottom: 4px;
}
.dt-callout-text { margin: 0; font-size: 13px; line-height: 1.55; color: var(--text); }

/* ── Responsive ── */
@media (max-width: 720px) {
  .dt-grid { grid-template-columns: 1fr; }
  .dt-hero-inner { flex-direction: column; }
  .dt-print { align-self: stretch; justify-content: center; }
  .dt-row { flex-direction: column; gap: 2px; }
  .dt-row-label { flex-basis: auto; }
}
@media (prefers-reduced-motion: reduce) {
  .dt-root * { transition: none !important; }
}
`;

// ═══════════════════════════════════════════════════════════════════════
// Print window HTML — branded, clean, A4-friendly, self-contained.
// ═══════════════════════════════════════════════════════════════════════

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

function buildPrintHtml(d: {
  companyName: string; companyCode: string; auditCode: string;
  auditees: Array<{ name: string; designation: string; email: string }>;
  contact: string; email: string; location: string;
  auditType: string; auditStage: string; auditMode: string;
  standards: string; accreditation: string; dateTime: string; coordinator: string;
  marketingRemarks: string; coordinatorRemarks: string; notes: string;
}): string {
  const auditeeRows = d.auditees.length
    ? d.auditees.map((a, i) => `
        <tr>
          <td class="idx">${i + 1}</td>
          <td class="nm">${esc(a.name)}</td>
          <td class="dg">${esc(a.designation || '—')}</td>
          <td class="em">${esc(a.email || '—')}</td>
        </tr>`).join('')
    : `<tr><td colspan="4" class="empty">No auditees recorded.</td></tr>`;

  const remarkBlock = (label: string, text: string, color: string) =>
    text ? `<div class="remark" style="border-left-color:${color}">
           <div class="remark-label" style="color:${color}">${esc(label)}</div>
           <div class="remark-text">${esc(text)}</div>
         </div>` : '';

  return `<!DOCTYPE html>
<html><head><meta charset="utf-8"><title>Audit Details — ${esc(d.companyName)}</title>
<style>
  * { box-sizing: border-box; }
  body { font-family: 'Segoe UI', Arial, sans-serif; color: #211a3a; margin: 0; padding: 34px; font-size: 12px; }
  .head { position: relative; border-bottom: 2px solid #160a33; padding: 0 0 16px; margin-bottom: 22px; }
  .head::before { content:''; position:absolute; top:-34px; left:-34px; right:-34px; height:4px;
    background: linear-gradient(90deg,#d4a017,#f0c14b 40%,rgba(240,193,75,0)); }
  .head-row { display:flex; justify-content:space-between; align-items:flex-start; gap: 24px; }
  .brand { font-size: 18px; font-weight: 800; color: #160a33; letter-spacing: .3px; }
  .brand small { display:block; font-size: 9.5px; font-weight: 700; color: #79728f; letter-spacing: .14em; text-transform: uppercase; margin-top: 5px; }
  .doc-meta { text-align: right; font-size: 11px; color: #79728f; line-height: 1.6; }
  .doc-meta b { color: #160a33; font-family: 'Courier New', monospace; }
  .facts { display:flex; gap: 10px; margin: 18px 0 4px; }
  .fact { flex:1; border: 1px solid #ece8f4; border-radius: 8px; padding: 9px 12px; }
  .fact .l { font-size: 8.5px; font-weight:700; letter-spacing:.1em; text-transform:uppercase; color:#79728f; }
  .fact .v { font-size: 12.5px; font-weight: 700; color:#160a33; margin-top: 3px; }
  h2 { font-size: 12px; color: #160a33; margin: 26px 0 10px; padding-bottom: 6px; border-bottom: 1px solid #ece8f4; text-transform: uppercase; letter-spacing: .07em; }
  .cols { display: flex; gap: 36px; }
  .cols > div { flex: 1; }
  table.kv { width:100%; border-collapse: collapse; }
  .kv td { padding: 6px 0; vertical-align: top; border-bottom: 1px solid #f3f0fa; }
  .kv tr:last-child td { border-bottom: none; }
  .kv td.k { color: #79728f; width: 32%; }
  .kv td.v { color: #211a3a; font-weight: 600; }
  table.aud { width:100%; border-collapse: collapse; border: 1px solid #ece8f4; border-radius: 8px; overflow: hidden; }
  table.aud th { background: #160a33; color: #fff; text-align: left; padding: 8px 12px; font-size: 9.5px; letter-spacing: .07em; text-transform: uppercase; }
  table.aud td { padding: 9px 12px; border-top: 1px solid #f1eef8; }
  table.aud td.idx { width: 36px; color: #b8b1cc; font-family: 'Courier New', monospace; }
  table.aud td.nm { font-weight: 700; color: #160a33; width: 34%; }
  table.aud td.dg { color: #4b4463; }
  table.aud td.em { color: #4b4463; }
  table.aud td.empty { text-align: center; color: #a39bb8; padding: 16px; }
  .remark { padding: 10px 14px; border-left: 4px solid; background: #faf9fc; border-radius: 0 6px 6px 0; margin: 8px 0; }
  .remark-label { font-size: 8.5px; font-weight: 700; text-transform: uppercase; letter-spacing: .07em; margin-bottom: 3px; }
  .remark-text { font-size: 12px; color: #211a3a; }
  .footer { margin-top: 32px; padding-top: 12px; border-top: 1px solid #ece8f4; font-size: 9.5px; color: #a39bb8; text-align: center; letter-spacing: .03em; }
  @page { margin: 15mm; }
</style></head>
<body>
  <div class="head">
    <div class="head-row">
      <div class="brand">QUALITY REGISTRAR SYSTEMS<small>Audit Detail Sheet</small></div>
      <div class="doc-meta">
        <div>Audit Code &nbsp;<b>${esc(d.auditCode)}</b></div>
        <div>${esc(d.dateTime)}</div>
        <div>Printed ${esc(new Date().toLocaleDateString('en-GB', { day: '2-digit', month: 'short', year: 'numeric' }))}</div>
      </div>
    </div>
    <div class="facts">
      <div class="fact"><div class="l">Type</div><div class="v">${esc(d.auditType)}</div></div>
      <div class="fact"><div class="l">Stage</div><div class="v">${esc(d.auditStage)}</div></div>
      <div class="fact"><div class="l">Mode</div><div class="v">${esc(d.auditMode)}</div></div>
      <div class="fact"><div class="l">Accreditation</div><div class="v">${esc(d.accreditation)}</div></div>
    </div>
  </div>

  <div class="cols">
    <div>
      <h2>Client</h2>
      <table class="kv">
        <tr><td class="k">Company</td><td class="v">${esc(d.companyName)}</td></tr>
        <tr><td class="k">Company code</td><td class="v">${esc(d.companyCode)}</td></tr>
        <tr><td class="k">Contact</td><td class="v">${esc(d.contact)}</td></tr>
        <tr><td class="k">Email</td><td class="v">${esc(d.email)}</td></tr>
        <tr><td class="k">Location</td><td class="v">${esc(d.location)}</td></tr>
      </table>
    </div>
    <div>
      <h2>Audit Scope</h2>
      <table class="kv">
        <tr><td class="k">Standards</td><td class="v">${esc(d.standards)}</td></tr>
        <tr><td class="k">Date &amp; time</td><td class="v">${esc(d.dateTime)}</td></tr>
        <tr><td class="k">Coordinator</td><td class="v">${esc(d.coordinator)}</td></tr>
      </table>
    </div>
  </div>

  <h2>Auditees / Attendees</h2>
  <table class="aud">
    <thead><tr><th>#</th><th>Name</th><th>Designation</th><th>Email</th></tr></thead>
    <tbody>${auditeeRows}</tbody>
  </table>

  ${remarkBlock('Marketing remarks', d.marketingRemarks, '#7c3aed')}
  ${remarkBlock('Coordinator notes', d.coordinatorRemarks, '#15803d')}
  ${remarkBlock('Audit notes', d.notes, '#b45309')}

  <div class="footer">Quality Registrar Systems — Audit Detail Sheet · Generated from CertifyHub</div>
</body></html>`;
}