// Print document — hidden in screen, shown via @media print when Export is clicked.
// Renders all four sections sequentially with consistent section headers,
// clean page breaks, and tables designed to flow across pages without orphaning.

function PrintDocument() {
  const r = window.READINESS;
  const cl = window.CLIENT;
  const next = window.RECOMMENDED_NEXT || {};

  const workflowsWithReadiness = (window.WORKFLOWS || []).map(w => ({
    ...w,
    readiness: window.computeReadiness ? window.computeReadiness(w) : null,
  }));

  const roadmapIds = new Set((window.ROADMAP || []).map(item => item.workflowRef).filter(Boolean));
  const deferred = workflowsWithReadiness.filter(
    w => !roadmapIds.has(w.id) && w.status !== 'Already handled'
  );

  const laborVal = Math.round(r.hoursRecoverable * (r.annualWagePlaceholder / r.fteHoursPerYear) / 1000);
  const laborDisplay = laborVal >= 1000 ? '$' + (laborVal / 1000).toFixed(1) + 'M' : '$' + laborVal + 'K';
  const fteDisplay = (r.hoursRecoverable / r.fteHoursPerYear).toFixed(1);

  // ── Sub-components ──────────────────────────────────────────────────────────

  function SectionHeader({ number, title }) {
    return (
      <div className="pd-section-header">
        <div className="pd-section-header-left">
          <div className="pd-section-header-meta">
            <span className="pd-section-header-client">{cl.name}</span>
            <span className="pd-section-header-sep">·</span>
            <span>AI Readiness Assessment</span>
            <span className="pd-section-header-sep">·</span>
            <span>Delivered by Linea · {cl.deliveredOn}</span>
          </div>
          <div className="pd-section-number">{number}</div>
          <div className="pd-section-title">{title}</div>
        </div>
        <div className="pd-section-linea">
          <span className="pd-linea-name">Linea</span>
          <span className="pd-linea-dot"></span>
        </div>
      </div>
    );
  }

  function TierBadge({ tier }) {
    const styles = {
      'Ready Now':    { background: '#e7f3ec', color: '#1a8f59' },
      'Needs Prep':   { background: '#f6eed7', color: '#a06d10' },
      'Longer-Term':  { background: '#ececea', color: '#5e6068' },
    };
    const s = styles[tier] || styles['Longer-Term'];
    return (
      <span className="pd-badge" style={s}>{tier}</span>
    );
  }

  function ReadinessBadge({ score, band }) {
    if (score == null) return <span className="pd-muted">—</span>;
    const styles = {
      'Ready to build':   { background: '#e7f3ec', color: '#1a8f59' },
      'Near-ready':       { background: '#f6eed7', color: '#a06d10' },
      'Discovery needed': { background: '#ececea', color: '#5e6068' },
    };
    const s = styles[band] || styles['Discovery needed'];
    return (
      <span className="pd-badge" style={s}>
        <b style={{ fontFamily: '"DM Serif Display", serif', fontSize: '1.15em' }}>{score}</b>
        {' · '}{band}
      </span>
    );
  }

  function PhaseBadge({ priority }) {
    const map = {
      'P0': { label: 'Phase 1', background: '#e4eaff', color: '#2e5dff' },
      'P1': { label: 'Phase 2', background: '#efeee9', color: '#3a3c42' },
      'P2': { label: 'Phase 3', background: '#efeee9', color: '#3a3c42' },
    };
    const s = map[priority] || { label: priority, background: '#ececea', color: '#5e6068' };
    return (
      <span className="pd-badge" style={{ background: s.background, color: s.color }}>
        {s.label}
      </span>
    );
  }

  function GovernanceBadge({ status }) {
    const styles = {
      'Approved':       { color: '#1a8f59' },
      'Needs setup':    { color: '#a06d10' },
      'Governance gap': { color: '#a73a3a' },
    };
    const s = styles[status] || {};
    return <span style={s}>{status}</span>;
  }

  function StaticScoreRing({ value, size = 148, stroke = 8 }) {
    const rx = (size - stroke) / 2;
    const circumference = 2 * Math.PI * rx;
    const offset = circumference - (value / 100) * circumference;
    return (
      <svg width={size} height={size} viewBox={`0 0 ${size} ${size}`}>
        <circle
          cx={size / 2} cy={size / 2} r={rx}
          stroke="rgba(10,10,10,0.08)" strokeWidth={stroke} fill="none"
        />
        <circle
          cx={size / 2} cy={size / 2} r={rx}
          stroke="#2e5dff" strokeWidth={stroke} fill="none"
          strokeDasharray={circumference}
          strokeDashoffset={offset}
          strokeLinecap="round"
          transform={`rotate(-90 ${size / 2} ${size / 2})`}
        />
      </svg>
    );
  }

  // ── Section 1: Executive Summary ───────────────────────────────────────────

  function Section1() {
    return (
      <div className="pd-section">
        <SectionHeader number="Section I" title="Executive Summary" />

        {/* Hero row: ring + lede + subscores */}
        <div className="pd-hero">
          {/* Score ring */}
          <div className="pd-hero-ring-wrap">
            <StaticScoreRing value={r.composite} />
            <div className="pd-hero-score-over">
              <div className="pd-hero-score-num">{r.composite}</div>
              <div className="pd-hero-score-denom">/100</div>
            </div>
            <div className="pd-hero-ring-label">Composite AI Readiness</div>
          </div>

          {/* Lede + phase */}
          <div className="pd-hero-mid">
            <p className="pd-hero-lede">{r.heroLabel}</p>
            <div className="pd-phase-box">
              <div className="pd-kicker">Recommended phase</div>
              <div className="pd-phase-value">{r.recommendedPhase}</div>
            </div>
          </div>

          {/* Subscores */}
          <div className="pd-subscores">
            {r.subscores.map(s => (
              <div key={s.key} className="pd-subscore">
                <div className="pd-subscore-head">
                  <span className="pd-subscore-label">{s.label}</span>
                  <span className="pd-subscore-val">
                    <span style={{ fontFamily: '"DM Serif Display", serif' }}>{s.value}</span>
                    <span className="pd-muted">/100</span>
                  </span>
                </div>
                <div className="pd-subscore-track">
                  <div className="pd-subscore-fill" style={{ width: s.value + '%' }} />
                </div>
                <div className="pd-subscore-note">{s.note}</div>
              </div>
            ))}
          </div>
        </div>

        {/* KPI row */}
        <div className="pd-kpis">
          <div className="pd-kpi">
            <div className="pd-kicker">Annual hours recoverable</div>
            <div className="pd-kpi-v">{r.hoursRecoverable.toLocaleString()}</div>
            <div className="pd-kpi-sub">Phase 1–3 roadmap. Full inventory: {r.totalInventoryHours.toLocaleString()} hrs total.</div>
          </div>
          <div className="pd-kpi">
            <div className="pd-kicker">Recoverable labour value</div>
            <div className="pd-kpi-v">{laborDisplay}<span className="pd-kpi-sup">*</span></div>
            <div className="pd-kpi-sub">*Based on ${Math.round(r.annualWagePlaceholder / 1000)}K annual wage.</div>
          </div>
          <div className="pd-kpi">
            <div className="pd-kicker">FTE-equivalent capacity</div>
            <div className="pd-kpi-v">{fteDisplay}<span className="pd-kpi-unit"> FTE</span></div>
            <div className="pd-kpi-sub">Hours freed as share of one full-time role / yr.</div>
          </div>
          <div className="pd-kpi">
            <div className="pd-kicker">Roadmap horizon</div>
            <div className="pd-kpi-v">{r.timelineMonths}<span className="pd-kpi-unit"> mo</span></div>
            <div className="pd-kpi-sub">From engagement start to full Phase 1 completion.</div>
          </div>
        </div>

        {/* Findings */}
        <div className="pd-subsection-label">Headline Findings</div>
        <div className="pd-findings">
          {(window.FINDINGS || []).map(f => (
            <div key={f.n} className="pd-finding">
              <div className="pd-finding-n">{f.n}</div>
              <div className="pd-finding-h">{f.headline}</div>
              <div className="pd-finding-p">{f.detail}</div>
            </div>
          ))}
        </div>
      </div>
    );
  }

  // ── Section 2: Data & Systems Readiness ────────────────────────────────────

  function Section2() {
    const sources = window.DATA_SOURCES || [];
    return (
      <div className="pd-section pd-section--break">
        <SectionHeader number="Section II" title="Data & Systems Readiness" />
        <p className="pd-lede">
          {sources.length} systems audited. Tier indicates readiness for AI integration —
          each system is assessed on accessibility, data structure, and governance posture.
        </p>

        <table className="pd-table">
          <thead>
            <tr>
              <th className="pd-th-system">System</th>
              <th>Dept</th>
              <th>Tier</th>
              <th>Data Quality</th>
              <th className="pd-th-wide">Finding</th>
              <th className="pd-th-action">Action</th>
            </tr>
          </thead>
          <tbody>
            {sources.map(ds => (
              <tr key={ds.name} className={ds.tier === 'Longer-Term' ? 'pd-tr-muted' : ''}>
                <td className="pd-td-bold">{ds.name}</td>
                <td>{ds.dept}</td>
                <td style={{ whiteSpace: 'nowrap' }}><TierBadge tier={ds.tier} /></td>
                <td>
                  <span style={{ display: 'block' }}>{ds.dataStructure}</span>
                  <GovernanceBadge status={ds.governance} />
                </td>
                <td>{ds.finding}</td>
                <td>{ds.action}</td>
              </tr>
            ))}
          </tbody>
        </table>

        <div className="pd-legend">
          <div className="pd-legend-item"><TierBadge tier="Ready Now" /> API accessible, schema clean, access provisioned. Connect immediately.</div>
          <div className="pd-legend-item"><TierBadge tier="Needs Prep" /> Format, access, or governance gap requires a data-prep sprint before use.</div>
          <div className="pd-legend-item"><TierBadge tier="Longer-Term" /> Structural blockers (legacy format, no API, compliance gap) require longer-horizon work.</div>
        </div>
      </div>
    );
  }

  // ── Section 3: Workflow Inventory ──────────────────────────────────────────

  function Section3() {
    const total = workflowsWithReadiness.reduce((s, w) => s + w.hours, 0);
    return (
      <div className="pd-section pd-section--break">
        <SectionHeader number="Section III" title="Workflow Inventory" />
        <p className="pd-lede">
          {workflowsWithReadiness.length} workflows mapped across {cl.name}, totalling{' '}
          {total.toLocaleString()} hours / year. Build readiness is a composite of
          process documentation completeness, dependent data tier, and output clarity.
        </p>

        <table className="pd-table">
          <thead>
            <tr>
              <th className="pd-th-idx">#</th>
              <th className="pd-th-workflow">Workflow</th>
              <th>Department</th>
              <th className="pd-th-num">Hrs / yr</th>
              <th>Status</th>
              <th>Build Readiness</th>
            </tr>
          </thead>
          <tbody>
            {workflowsWithReadiness.map((w, i) => (
              <tr key={w.id} className={w.status === 'Already handled' ? 'pd-tr-muted' : ''}>
                <td className="pd-td-idx">{String(i + 1).padStart(2, '0')}</td>
                <td className="pd-td-bold">{w.name}</td>
                <td>{w.dept}</td>
                <td className="pd-td-num">{w.hours.toLocaleString()}</td>
                <td>{w.status}</td>
                <td>
                  {w.readiness
                    ? <ReadinessBadge score={w.readiness.composite} band={w.readiness.band} />
                    : <span className="pd-muted">—</span>}
                </td>
              </tr>
            ))}
          </tbody>
        </table>

        <div className="pd-legend">
          <div className="pd-legend-item"><span className="pd-badge" style={{ background: '#e7f3ec', color: '#1a8f59' }}>Ready to build</span> Score ≥ 80. Process documented, data accessible, output well-defined.</div>
          <div className="pd-legend-item"><span className="pd-badge" style={{ background: '#f6eed7', color: '#a06d10' }}>Near-ready</span> Score 60–79. Minor prep required — typically one data or process gap to close.</div>
          <div className="pd-legend-item"><span className="pd-badge" style={{ background: '#ececea', color: '#5e6068' }}>Discovery needed</span> Score &lt; 60. Prerequisites must be resolved before build can start.</div>
        </div>
      </div>
    );
  }

  // ── Section 4: Execution Roadmap ───────────────────────────────────────────

  function Section4() {
    const roadmap = window.ROADMAP || [];
    const p0 = roadmap.filter(r => r.priority === 'P0');
    const p1 = roadmap.filter(r => r.priority === 'P1');
    const p2 = roadmap.filter(r => r.priority === 'P2');

    return (
      <div className="pd-section pd-section--break">
        <SectionHeader number="Section IV" title="Execution Roadmap" />
        <p className="pd-lede">
          {roadmap.length} recommended workflows across three phases, ordered by Linea's
          assessment of readiness and return.
          {deferred.length > 0 && ` ${deferred.length} additional workflow${deferred.length !== 1 ? 's' : ''} deferred pending prerequisites.`}
        </p>

        {/* Recommended next step */}
        <div className="pd-nextstep">
          <div className="pd-nextstep-main">
            <div className="pd-kicker" style={{ color: '#2e5dff' }}>Recommended Next Step</div>
            <div className="pd-nextstep-title">{next.title}</div>
            <p className="pd-nextstep-body">{next.body}</p>
          </div>
          <div className="pd-nextstep-stats">
            <div className="pd-nextstep-stat">
              <div className="pd-kicker">Expected return</div>
              <div className="pd-nextstep-stat-v">{(next.returnHours || 0).toLocaleString()}</div>
              <div className="pd-nextstep-stat-l">{next.returnLabel || 'hours / year recovered'}</div>
            </div>
            <div className="pd-nextstep-stat">
              <div className="pd-kicker">Time to first value</div>
              <div className="pd-nextstep-stat-v">
                {next.timeToValue || 6}
                <span style={{ fontSize: '0.5em', marginLeft: 3 }}>{next.timeToValueUnit || 'wk'}</span>
              </div>
              <div className="pd-nextstep-stat-l">{next.timeToValueLabel || 'first usable draft in hands'}</div>
            </div>
          </div>
        </div>

        {/* Phase summary counts */}
        <div className="pd-phase-counts">
          <div className="pd-phase-count">
            <span className="pd-badge" style={{ background: '#e4eaff', color: '#2e5dff' }}>Phase 1</span>
            <b>{p0.length} workflow{p0.length !== 1 ? 's' : ''}</b>
          </div>
          <div className="pd-phase-count">
            <span className="pd-badge" style={{ background: '#efeee9', color: '#3a3c42' }}>Phase 2</span>
            <b>{p1.length} workflow{p1.length !== 1 ? 's' : ''}</b>
          </div>
          <div className="pd-phase-count">
            <span className="pd-badge" style={{ background: '#efeee9', color: '#3a3c42' }}>Phase 3</span>
            <b>{p2.length} workflow{p2.length !== 1 ? 's' : ''}</b>
          </div>
          {deferred.length > 0 && (
            <div className="pd-phase-count">
              <span className="pd-badge" style={{ background: '#ececea', color: '#5e6068' }}>Deferred</span>
              <b>{deferred.length}</b>
            </div>
          )}
        </div>

        <table className="pd-table">
          <thead>
            <tr>
              <th>Phase</th>
              <th className="pd-th-workflow">Workflow</th>
              <th className="pd-th-wide">Rationale</th>
              <th>Effort</th>
              <th className="pd-th-wide">Impact</th>
              <th>Delivery Model</th>
            </tr>
          </thead>
          <tbody>
            {roadmap.map((item) => (
              <tr key={item.id}>
                <td style={{ whiteSpace: 'nowrap' }}><PhaseBadge priority={item.priority} /></td>
                <td className="pd-td-bold">{item.title}</td>
                <td>{item.rationale}</td>
                <td style={{ whiteSpace: 'nowrap' }}>{item.effort}</td>
                <td>{item.impact}</td>
                <td>{item.model}</td>
              </tr>
            ))}
            {deferred.map(w => (
              <tr key={w.id} className="pd-tr-muted">
                <td>
                  <span className="pd-badge" style={{ background: '#ececea', color: '#5e6068' }}>Deferred</span>
                </td>
                <td className="pd-td-bold">{w.name}</td>
                <td colSpan={4}>Pending prerequisites — not scheduled in current roadmap</td>
              </tr>
            ))}
          </tbody>
        </table>

        {/* Document footer */}
        <div className="pd-doc-footer">
          <div className="pd-footer-linea">
            <span className="pd-linea-name">Linea</span>
            <span className="pd-linea-dot"></span>
          </div>
          <div className="pd-footer-meta">
            Prepared for {cl.name} · {cl.deliveredOn} · Engagement lead: {cl.engagementLead} · bylinea.com
          </div>
        </div>
      </div>
    );
  }

  // ── Section 5: System Fact Sheets ─────────────────────────────────────────

  const DATA_OBJECTS = window.DATA_OBJECTS || {};

  const SENSITIVITY_COLOR = {
    'Business':  '#2e5dff',
    'Personal':  '#a06d10',
    'Financial': '#1a8f59',
    'Public':    '#5e6068',
  };

  const TAG_COLOR = {
    'Key detail':    '#2e5dff',
    'AI-ready':      '#1a8f59',
    'Personal info': '#a06d10',
    'Financial':     '#0f7a6b',
    'Free text':     '#6b6e76',
    'Often blank':   '#a73a3a',
  };

  const FRESHNESS_RANK = { 'Live': 6, 'High volume': 6, 'Daily': 5, 'Weekly': 4, 'Monthly': 3, 'Quarterly': 2 };

  function deriveTrust(ds) {
    const cat = DATA_OBJECTS[ds.name] || {};
    const objs = cat.objects || [];

    const qualityMap = {
      'Ready Now':   { label: 'Good',       color: '#1a8f59' },
      'Needs Prep':  { label: 'Needs prep', color: '#b07a18' },
      'Longer-Term': { label: 'Limited',    color: '#7a7d85' },
    };
    const quality = qualityMap[ds.tier] || qualityMap['Longer-Term'];

    let bestRank = 0, freshLabel = '—';
    objs.forEach(o => {
      const r = FRESHNESS_RANK[o.updated] || 1;
      if (r > bestRank) { bestRank = r; freshLabel = o.updated; }
    });
    const freshColor = bestRank >= 5 ? '#1a8f59' : bestRank >= 3 ? '#b07a18' : '#7a7d85';

    const sensRank = { 'Personal': 4, 'Financial': 3, 'Business': 2, 'Public': 1 };
    let topSens = 'Business', topRank = 0;
    objs.forEach(o => {
      const r = sensRank[o.sensitivity] || 0;
      if (r > topRank) { topRank = r; topSens = o.sensitivity; }
    });

    const allFeeds = [...new Set(objs.flatMap(o => o.feeds || []))];

    return { quality, freshLabel, freshColor, topSens, allFeeds };
  }

  function SystemFactSheet({ ds, isFirst }) {
    const cat = DATA_OBJECTS[ds.name] || {};
    const objs = cat.objects || [];
    const trust = deriveTrust(ds);
    const tierStyle = {
      'Ready Now':   { background: '#e7f3ec', color: '#1a8f59' },
      'Needs Prep':  { background: '#f6eed7', color: '#a06d10' },
      'Longer-Term': { background: '#ececea', color: '#5e6068' },
    };
    const ts = tierStyle[ds.tier] || tierStyle['Longer-Term'];

    return (
      <div className={'pd-section' + (isFirst ? '' : ' pd-section--break')}>
        <SectionHeader number="Section V" title="System Fact Sheets" />

        {/* System title row */}
        <div className="pd-fs-titlerow">
          <div className="pd-fs-title">{ds.name}</div>
          <span className="pd-badge" style={ts}>{ds.tier}</span>
        </div>
        <div className="pd-fs-meta">
          <span>{ds.category}</span>
          <span className="pd-fs-meta-sep">·</span>
          <span>Owner: {ds.owner}</span>
          <span className="pd-fs-meta-sep">·</span>
          <span>{ds.location}</span>
          <span className="pd-fs-meta-sep">·</span>
          <span>{ds.format}</span>
        </div>
        {cat.summary && <p className="pd-fs-summary">{cat.summary}</p>}

        {/* Trust signals */}
        <div className="pd-fs-signals">
          <div className="pd-fs-signal">
            <div className="pd-kicker">Data quality</div>
            <div className="pd-fs-signal-val">
              <span className="pd-fs-dot" style={{ background: trust.quality.color }} />
              {trust.quality.label}
            </div>
          </div>
          <div className="pd-fs-signal">
            <div className="pd-kicker">Freshness</div>
            <div className="pd-fs-signal-val">
              <span className="pd-fs-dot" style={{ background: trust.freshColor }} />
              {trust.freshLabel}
            </div>
          </div>
          <div className="pd-fs-signal">
            <div className="pd-kicker">Owned by</div>
            <div className="pd-fs-signal-val">{ds.owner}</div>
          </div>
          <div className="pd-fs-signal">
            <div className="pd-kicker">Sensitivity</div>
            <div className="pd-fs-signal-val">
              <span className="pd-fs-dot" style={{ background: SENSITIVITY_COLOR[trust.topSens] || '#5e6068' }} />
              {trust.topSens}
            </div>
          </div>
        </div>

        {/* Finding + action */}
        <div className="pd-fs-audit">
          <div className="pd-fs-audit-item">
            <div className="pd-kicker">Audit finding</div>
            <div className="pd-fs-audit-body">{ds.finding}</div>
          </div>
          <div className="pd-fs-audit-item">
            <div className="pd-kicker">Recommended action</div>
            <div className="pd-fs-audit-body">{ds.action}</div>
          </div>
        </div>

        {/* Record types */}
        {objs.length > 0 ? (
          <div className="pd-fs-objects">
            <div className="pd-subsection-label">What it holds</div>
            {objs.map(obj => {
              const sensColor = SENSITIVITY_COLOR[obj.sensitivity] || '#5e6068';
              const keyFields = obj.fields.filter(f => f.tags && (f.tags.includes('Key detail') || f.tags.includes('AI-ready')));
              const shownFields = keyFields.length > 0 ? obj.fields : obj.fields.slice(0, 6);
              return (
                <div key={obj.name} className="pd-fs-object">
                  <div className="pd-fs-object-head">
                    <div className="pd-fs-object-name">{obj.name}</div>
                    <div className="pd-fs-object-meta">
                      <span style={{ color: sensColor, fontWeight: 600, fontSize: '7.5pt' }}>{obj.sensitivity}</span>
                      <span className="pd-fs-meta-sep">·</span>
                      <span>{obj.records} records</span>
                      <span className="pd-fs-meta-sep">·</span>
                      <span>Updated: {obj.updated}</span>
                    </div>
                    {obj.blurb && <div className="pd-fs-object-blurb">{obj.blurb}</div>}
                  </div>
                  <table className="pd-table pd-fs-fields-table">
                    <thead>
                      <tr>
                        <th style={{ width: '22%' }}>Field</th>
                        <th>Description</th>
                        <th style={{ width: '20%' }}>Example</th>
                        <th style={{ width: '12%' }}>Type</th>
                        <th style={{ width: '14%' }}>Tags</th>
                      </tr>
                    </thead>
                    <tbody>
                      {shownFields.map(f => (
                        <tr key={f.name}>
                          <td className="pd-td-bold">{f.name}</td>
                          <td>{f.desc}</td>
                          <td className="pd-muted" style={{ fontStyle: 'italic' }}>{f.example}</td>
                          <td className="pd-muted">{f.type}</td>
                          <td>
                            {(f.tags || []).map(t => (
                              <span key={t} style={{
                                display: 'inline-block', marginRight: 3, marginBottom: 2,
                                padding: '1pt 5pt', borderRadius: 3,
                                fontSize: '7pt', fontWeight: 600,
                                background: (TAG_COLOR[t] || '#6b6e76') + '18',
                                color: TAG_COLOR[t] || '#6b6e76',
                              }}>{t}</span>
                            ))}
                          </td>
                        </tr>
                      ))}
                    </tbody>
                  </table>
                  {obj.feeds && obj.feeds.length > 0 && (
                    <div className="pd-fs-feeds">
                      <span className="pd-kicker" style={{ marginRight: 8 }}>Powers:</span>
                      {obj.feeds.map(f => (
                        <span key={f} className="pd-fs-feed-chip">{f}</span>
                      ))}
                    </div>
                  )}
                </div>
              );
            })}
          </div>
        ) : cat.note ? (
          <div className="pd-fs-note">
            <div className="pd-subsection-label">System note</div>
            <p>{cat.note}</p>
          </div>
        ) : null}
      </div>
    );
  }

  function Section5() {
    const sources = window.DATA_SOURCES || [];
    return (
      <React.Fragment>
        {sources.map((ds, i) => (
          <SystemFactSheet key={ds.name} ds={ds} isFirst={i === 0} />
        ))}
      </React.Fragment>
    );
  }

  // ── Section 6: Workflow SOPs ───────────────────────────────────────────────

  const SOPS = window.SOPS || {};

  const RACI_COLOR = {
    'Accountable': '#2e5dff',
    'Responsible': '#1a8f59',
    'Consulted':   '#a06d10',
    'Informed':    '#6b6e76',
  };

  const SOP_STATUS_COLOR = {
    'Current':       '#1a8f59',
    'Draft':         '#a06d10',
    'In review':     '#2e5dff',
    'Not documented':'#a73a3a',
  };

  function SopPage({ w, isFirst }) {
    const sop = SOPS[w.id];
    const readiness = window.computeReadiness ? window.computeReadiness(w) : null;

    return (
      <div className={'pd-section' + (isFirst ? '' : ' pd-section--break')}>
        <SectionHeader number="Section VI" title="Workflow SOPs" />

        {sop ? <SopFull w={w} sop={sop} /> : <SopGap w={w} readiness={readiness} />}
      </div>
    );
  }

  function SopFull({ w, sop }) {
    const statusColor = SOP_STATUS_COLOR[sop.status] || '#5e6068';
    const statusBg = statusColor + '18';

    let letter = 64; // 'A' - 1
    function nextLetter() { letter++; return String.fromCharCode(letter); }

    return (
      <div className="pd-sop">
        {/* Document control block */}
        <div className="pd-sop-control">
          <div className="pd-sop-control-bar">
            <div className="pd-sop-control-title">{sop.title}</div>
            <div className="pd-sop-control-right">
              <span className="pd-badge" style={{ background: 'rgba(255,255,255,0.15)', color: '#fff', marginRight: 8 }}>{sop.code}</span>
              <span className="pd-badge" style={{ background: statusBg, color: statusColor, filter: 'brightness(1.5)' }}>{sop.status}</span>
            </div>
          </div>
          <div className="pd-sop-control-grid">
            <div className="pd-sop-cell"><div className="pd-kicker">Process owner</div><div>{sop.owner}</div></div>
            <div className="pd-sop-cell"><div className="pd-kicker">Approver</div><div>{sop.approver}</div></div>
            <div className="pd-sop-cell"><div className="pd-kicker">Version</div><div>{sop.version}</div></div>
            <div className="pd-sop-cell"><div className="pd-kicker">Last reviewed</div><div>{sop.lastReviewed}</div></div>
            <div className="pd-sop-cell"><div className="pd-kicker">Frequency</div><div>{sop.frequency}</div></div>
            <div className="pd-sop-cell"><div className="pd-kicker">Department</div><div>{w.dept}</div></div>
          </div>
        </div>

        {/* Purpose / Scope / Trigger */}
        <div className="pd-sop-pst">
          <div className="pd-sop-pst-item">
            <div className="pd-sop-sec-label">{nextLetter()} · Purpose</div>
            <p className="pd-sop-body">{sop.purpose}</p>
          </div>
          <div className="pd-sop-pst-item">
            <div className="pd-sop-sec-label">{nextLetter()} · Scope</div>
            <p className="pd-sop-body">{sop.scope}</p>
          </div>
          <div className="pd-sop-pst-item">
            <div className="pd-sop-sec-label">{nextLetter()} · Trigger</div>
            <p className="pd-sop-body">{sop.trigger}</p>
          </div>
        </div>

        {/* Roles */}
        {sop.roles && sop.roles.length > 0 && (
          <div className="pd-sop-section">
            <div className="pd-sop-sec-label">{nextLetter()} · Roles &amp; Responsibilities</div>
            <table className="pd-table">
              <thead>
                <tr>
                  <th style={{ width: '18%' }}>Role</th>
                  <th style={{ width: '18%' }}>Who</th>
                  <th>Responsibility</th>
                  <th style={{ width: '12%' }}>RACI</th>
                </tr>
              </thead>
              <tbody>
                {sop.roles.map((r, i) => (
                  <tr key={i}>
                    <td className="pd-td-bold">{r.role}</td>
                    <td>{r.who}</td>
                    <td>{r.responsibility}</td>
                    <td>
                      <span style={{
                        display: 'inline-block', padding: '2pt 7pt', borderRadius: 3,
                        fontSize: '7.5pt', fontWeight: 700,
                        background: (RACI_COLOR[r.tag] || '#6b6e76') + '18',
                        color: RACI_COLOR[r.tag] || '#6b6e76',
                      }}>{r.tag}</span>
                    </td>
                  </tr>
                ))}
              </tbody>
            </table>
          </div>
        )}

        {/* Procedure steps */}
        {sop.steps && sop.steps.length > 0 && (
          <div className="pd-sop-section">
            <div className="pd-sop-sec-label">{nextLetter()} · Procedure</div>
            <div className="pd-sop-steps">
              {sop.steps.map((step, i) => (
                <div key={i} className="pd-sop-step">
                  <div className="pd-sop-step-num">{i + 1}</div>
                  <div className="pd-sop-step-body">
                    <div className="pd-sop-step-title">{step.title}</div>
                    <div className="pd-sop-step-detail">{step.detail}</div>
                    <div className="pd-sop-step-meta">
                      {step.role && <span><span className="pd-sop-step-meta-l">Who</span>{step.role}</span>}
                      {step.system && step.system !== '—' && <span><span className="pd-sop-step-meta-l">System</span>{step.system}</span>}
                      {step.output && <span><span className="pd-sop-step-meta-l">Output</span>{step.output}</span>}
                    </div>
                  </div>
                </div>
              ))}
            </div>
          </div>
        )}

        {/* Inputs & Outputs */}
        {(sop.inputs || sop.outputs) && (
          <div className="pd-sop-section">
            <div className="pd-sop-sec-label">{nextLetter()} · Inputs &amp; Outputs</div>
            <div className="pd-sop-io">
              <div className="pd-sop-io-col">
                <div className="pd-sop-io-head">Inputs</div>
                <ul className="pd-sop-list">
                  {(sop.inputs || []).map((item, i) => <li key={i}>{item}</li>)}
                </ul>
              </div>
              <div className="pd-sop-io-arrow">→</div>
              <div className="pd-sop-io-col">
                <div className="pd-sop-io-head">Outputs</div>
                <ul className="pd-sop-list">
                  {(sop.outputs || []).map((item, i) => <li key={i}>{item}</li>)}
                </ul>
              </div>
            </div>
          </div>
        )}

        {/* Systems used */}
        {sop.systems && sop.systems.length > 0 && (
          <div className="pd-sop-section">
            <div className="pd-sop-sec-label">{nextLetter()} · Systems Used</div>
            <div className="pd-sop-chips">
              {sop.systems.map(s => {
                const srcDs = (window.DATA_SOURCES || []).find(d => d.name === s);
                const tierStyle = { 'Ready Now': { background: '#e7f3ec', color: '#1a8f59' }, 'Needs Prep': { background: '#f6eed7', color: '#a06d10' }, 'Longer-Term': { background: '#ececea', color: '#5e6068' } };
                const ts = srcDs ? (tierStyle[srcDs.tier] || {}) : {};
                return (
                  <span key={s} className="pd-sop-sys-chip">
                    {s}
                    {srcDs && <span className="pd-badge" style={{ ...ts, marginLeft: 5, fontSize: '7pt' }}>{srcDs.tier}</span>}
                  </span>
                );
              })}
            </div>
          </div>
        )}

        {/* Exceptions */}
        {sop.exceptions && sop.exceptions.length > 0 && (
          <div className="pd-sop-section">
            <div className="pd-sop-sec-label">{nextLetter()} · Exceptions &amp; Edge Cases</div>
            <table className="pd-table">
              <thead>
                <tr>
                  <th style={{ width: '40%' }}>If</th>
                  <th>Then</th>
                </tr>
              </thead>
              <tbody>
                {sop.exceptions.map((ex, i) => (
                  <tr key={i}>
                    <td className="pd-td-bold">{ex.when}</td>
                    <td>{ex.then}</td>
                  </tr>
                ))}
              </tbody>
            </table>
          </div>
        )}

        {/* Quality checks */}
        {sop.quality && sop.quality.length > 0 && (
          <div className="pd-sop-section">
            <div className="pd-sop-sec-label">{nextLetter()} · Quality Checks</div>
            <ul className="pd-sop-quality">
              {sop.quality.map((q, i) => <li key={i}>{q}</li>)}
            </ul>
          </div>
        )}

        {/* Revision history */}
        {sop.revisions && sop.revisions.length > 0 && (
          <div className="pd-sop-section pd-sop-section--minor">
            <div className="pd-sop-sec-label pd-sop-sec-label--minor">Revision History</div>
            <table className="pd-table">
              <thead>
                <tr>
                  <th style={{ width: '12%' }}>Version</th>
                  <th style={{ width: '18%' }}>Date</th>
                  <th style={{ width: '22%' }}>By</th>
                  <th>Change</th>
                </tr>
              </thead>
              <tbody>
                {sop.revisions.map((row, i) => (
                  <tr key={i}>
                    <td>{row[0]}</td>
                    <td>{row[1]}</td>
                    <td>{row[2]}</td>
                    <td>{row[3]}</td>
                  </tr>
                ))}
              </tbody>
            </table>
          </div>
        )}
      </div>
    );
  }

  function SopGap({ w, readiness }) {
    return (
      <div className="pd-sop pd-sop--gap">
        {/* Workflow identity */}
        <div className="pd-sop-gap-head">
          <div className="pd-sop-gap-name">{w.name}</div>
          <div className="pd-fs-meta">
            <span>{w.dept}</span>
            <span className="pd-fs-meta-sep">·</span>
            <span>{w.hours.toLocaleString()} hrs / yr</span>
            <span className="pd-fs-meta-sep">·</span>
            <span>{w.status}</span>
          </div>
        </div>

        {/* Readiness + process note */}
        <div className="pd-sop-gap-signals">
          {readiness && (
            <div className="pd-fs-signal">
              <div className="pd-kicker">Build readiness</div>
              <div className="pd-fs-signal-val">
                <span className="pd-fs-dot" style={{ background: readiness.composite >= 80 ? '#1a8f59' : readiness.composite >= 60 ? '#b07a18' : '#7a7d85' }} />
                <b style={{ fontFamily: '"DM Serif Display", serif', fontSize: '13pt' }}>{readiness.composite}</b>
                <span className="pd-muted" style={{ marginLeft: 4 }}>· {readiness.band}</span>
              </div>
            </div>
          )}
          <div className="pd-fs-signal">
            <div className="pd-kicker">Process documentation</div>
            <div className="pd-fs-signal-val">
              <b style={{ fontFamily: '"DM Serif Display", serif', fontSize: '13pt' }}>{w.processDoc || 0}%</b>
              <span className="pd-muted" style={{ marginLeft: 4 }}>complete</span>
            </div>
          </div>
        </div>

        {w.processNote && (
          <div className="pd-sop-gap-note">
            <div className="pd-kicker">Documentation status</div>
            <p className="pd-sop-body">{w.processNote}</p>
          </div>
        )}

        {/* Current / Proposed / Impact */}
        <div className="pd-sop-gap-sections">
          {w.current && (
            <div>
              <div className="pd-sop-sec-label">Current process</div>
              <p className="pd-sop-body">{w.current}</p>
            </div>
          )}
          {w.proposed && (
            <div>
              <div className="pd-sop-sec-label">Proposed AI approach</div>
              <p className="pd-sop-body">{w.proposed}</p>
            </div>
          )}
          {w.impact && (
            <div>
              <div className="pd-sop-sec-label">Expected impact</div>
              <p className="pd-sop-body">{w.impact}</p>
            </div>
          )}
        </div>

        {/* Data dependencies */}
        {w.dependsOn && w.dependsOn.length > 0 && (
          <div>
            <div className="pd-sop-sec-label">Data dependencies</div>
            <div className="pd-sop-chips">
              {w.dependsOn.map(dep => {
                const srcDs = (window.DATA_SOURCES || []).find(d => d.name === dep);
                const tierStyle = { 'Ready Now': { background: '#e7f3ec', color: '#1a8f59' }, 'Needs Prep': { background: '#f6eed7', color: '#a06d10' }, 'Longer-Term': { background: '#ececea', color: '#5e6068' } };
                const ts = srcDs ? (tierStyle[srcDs.tier] || {}) : {};
                return (
                  <span key={dep} className="pd-sop-sys-chip">
                    {dep}
                    {srcDs && <span className="pd-badge" style={{ ...ts, marginLeft: 5, fontSize: '7pt' }}>{srcDs.tier}</span>}
                  </span>
                );
              })}
            </div>
          </div>
        )}

        <div className="pd-sop-gap-notice">
          This workflow does not yet have a formally documented SOP. The process description above is derived from the assessment interviews. Documenting this workflow in full is a prerequisite for AI deployment.
        </div>
      </div>
    );
  }

  function Section6() {
    const workflows = window.WORKFLOWS || [];
    return (
      <React.Fragment>
        {workflows.map((w, i) => (
          <SopPage key={w.id} w={w} isFirst={i === 0} />
        ))}
      </React.Fragment>
    );
  }

  // ── Root render ─────────────────────────────────────────────────────────────

  return (
    <div className="print-document">
      <Section1 />
      <Section2 />
      <Section3 />
      <Section4 />
      <Section5 />
      <Section6 />
    </div>
  );
}

window.PrintDocument = PrintDocument;
