/* ================================================================
 * Registry Review — synthetic seed + pure state transitions.
 *
 * Synthetic data only (Nzioki, 15 Oct 2026). Every value is shaped on
 * the EcoGreen Bamboo material already in this repo (data.jsx,
 * src/lib/projects.ts, field-agent-v2/config.jsx). No real PDD
 * content, farmer names, coordinates or figures.
 *
 * One finding shape serves both layers:
 *   layer 'registry_to_vvb'   — Verra reviewer raises, VVB responds, Verra closes
 *   layer 'vvb_to_developer'  — VVB raises CAR / CL / FAR during validation
 *
 * Status machine:
 *   raised -> pending_vvb -> pending_developer -> pending_vvb
 *          -> pending_registry -> closed | pending_vvb (next round)
 *
 * A finding is scoped to one document (scope_document): the Project
 * Description, the Monitoring Report, or the VVB's validation or
 * verification report. Verra suffixes the title with the document
 * ("Project Location – Monitoring Report"); findingTitle() does the same.
 * A registry response may carry per-item outcomes (items[]), so item 2
 * can close while item 1 stays open in the same round (Verra 3197,
 * findings 7 and 9).
 *
 * Section numbers follow the VCS Project Description Template v4.4 and
 * the VCS Monitoring Report Template v4.4, the versions in force until
 * the 1 Jan 2027 change. Every program-rule
 * citation was verified on 15 Oct 2026 against VCS Standard v4.7
 * (16 April 2024), VCS Project Description Template v4.4 and the
 * full-text verified VM0047 v1.1 index in the platform repo
 * (docs/reference/methodologies/verra-vm0047-v1.1.md). The record is
 * in docs/design-brief-registry-review.md section 14. A citation shows
 * VERIFY only when it is raised live against a section that is not in
 * VERIFIED_SECTIONS below.
 * ================================================================ */

/* ------ PD structure for EcoGreen (VCS Project Description Template v4.4 numbering and titles, verified 15 Oct 2026) ------ */
const PD_SECTIONS = [
  { num:'1', title:'Project Details', items:[
    { num:'1.1',  title:'Summary Description of the Project', field_id:null,
      narrative:'Pamoja EcoGreen Bamboo restores degraded smallholder land in Bungoma County, western Kenya, with native and naturalised bamboo under VM0047. The project works with 1,840 households across three strata.' },
    { num:'1.9',  title:'Project Start Date', field_id:null, narrative:'12 March 2025, the date of the first planting under the project activity.' },
    { num:'1.10', title:'Project Crediting Period', field_id:null, narrative:'30 years, 12 March 2025 to 11 March 2055, renewable per the VCS Standard.' },
    { num:'1.11', title:'Project Scale and Estimated GHG Emission Reductions or Removals', field_id:null, narrative:'Large project. Estimated average annual net GHG emission reductions of 4,744 tCO2e over the crediting period.' },
    { num:'1.13', title:'Project Location', field_id:'area',
      narrative:'The project area covers 12,000 ha in Bungoma County, Kenya, centred on 0.5635 N, 34.5606 E. The boundary is defined by the KML file in document 27. Table 1, row 5 states the total eligible area.' },
    { num:'1.15', title:'Compliance with Laws, Statutes and Other Regulatory Frameworks', field_id:null, narrative:'The project complies with the Climate Change Act 2016 and the Forest Conservation and Management Act 2016 of Kenya.' },
  ]},
  { num:'2', title:'Safeguards and Stakeholder Engagement', items:[
    { num:'2.1.2', title:'Stakeholder Consultation and Ongoing Communication', field_id:'consent',
      narrative:'Local stakeholder consultations were held in each of the four sub-counties during 2024. Participants were informed of the project design, risks and benefits, and free, prior and informed consent was recorded.' },
    { num:'2.2', title:'Risks to Stakeholders and the Environment', field_id:'safeguards', narrative:'An environmental and social risk screening identified no net harm pathways. Eight of eight SDG markers are addressed.' },
    { num:'2.3.4', title:'Property Rights', field_id:'tenure', narrative:'Land tenure is customary with statutory recognition. Tenure records are held by the co-operative.' },
  ]},
  { num:'3', title:'Application of Methodology', items:[
    { num:'3.1', title:'Title and Reference of Methodology', field_id:'method', narrative:'VM0047 Afforestation, Reforestation and Revegetation, v1.1, Verra.' },
    { num:'3.3', title:'Project Boundary', field_id:'boundary', narrative:'The project boundary is the geographic boundary in document 27 plus the carbon pools above-ground biomass, below-ground biomass and soil organic carbon.' },
    { num:'3.5', title:'Additionality', field_id:'addnl', narrative:'Additionality is demonstrated through investment analysis and barrier analysis as required by the methodology.' },
  ]},
  { num:'4', title:'Quantification of Estimated GHG Emission Reductions and Removals', items:[
    { num:'4.1', title:'Baseline Emissions', field_id:'stratify',
      narrative:'Baseline carbon stocks were estimated by stratum. Stratum A (lowland) 20 plots, Stratum B (riparian) 8 plots, Stratum C (mid-slope) 14 plots. Plot-level data are in document 28.' },
    { num:'4.3', title:'Leakage Emissions', field_id:'leakage', narrative:'A 0.5 km leakage belt of 412 ha surrounds the project area and is monitored for activity-shifting leakage.' },
  ]},
  { num:'5', title:'Monitoring', items:[
    { num:'5.3', title:'Monitoring Plan', field_id:'monitoring', narrative:'Annual monitoring with a full re-inventory every five years. Field agents capture plot data quarterly for the first three vintages.' },
  ]},
];

/* ------ Monitoring Report structure for EcoGreen, monitoring period 1 (VCS Monitoring Report Template v4.4 numbering and titles, verified 15 Oct 2026) ------ */
const MR_SECTIONS = [
  { num:'1', title:'Project Details', items:[
    { num:'1.1', title:'Summary Description of the Implementation Status of the Project', field_id:null,
      narrative:'Monitoring period 1 runs from 12 March 2025 to 11 March 2026. Planting was completed in all three strata and 1,840 planting-unit records were captured by field agents at the first monitoring event. No deviation from the validated Project Description is reported.' },
    { num:'1.8', title:'Project Location', field_id:'planting_units',
      narrative:'The project boundary is unchanged from the Project Description: 12,450 ha in Bungoma County, Kenya, defined by the KML in document 27. Planting units were established in all three strata inside the boundary during the monitoring period.' },
    { num:'1.9', title:'Title and Reference of Methodology', field_id:null, narrative:'VM0047 Afforestation, Reforestation and Revegetation, v1.1, Verra. No methodology deviation was applied in this monitoring period.' },
  ]},
  { num:'2', title:'Safeguards and Stakeholder Engagement', items:[
    { num:'2.1.4', title:'Grievance Redress Procedure', field_id:null, narrative:'Three grievances were logged with the co-operative during the period, all concerning planting-unit boundaries between neighbouring households. Each was resolved by the sub-county committee within 30 days. The grievance log is held by the co-operative and was inspected by the VVB.' },
  ]},
  { num:'3', title:'Implementation Status', items:[
    { num:'3.1', title:'Implementation Status of the Project Activity', field_id:null, narrative:'Planting began on 12 March 2025. By 11 March 2026 all planned planting units had been established. Survival at the first monitoring event was 91 percent, with mortality concentrated in Stratum B (riparian) after the October 2025 floods.' },
    { num:'3.2.2', title:'Project Description Deviations', field_id:null, narrative:'None. The project activity was implemented as described in the validated Project Description.' },
  ]},
  { num:'4', title:'Data and Parameters', items:[
    { num:'4.2', title:'Data and Parameters Monitored', field_id:null, narrative:'For each planting unit: unique ID, georeferenced point, year planted, species and survival status, captured by field agents at the first monitoring event in February 2026. Woody biomass was not measured in this period; the first biomass measurement is scheduled for monitoring period 2.' },
    { num:'4.3', title:'Monitoring Plan', field_id:null, narrative:'Monitoring follows the plan in Section 5.3 of the Project Description: annual monitoring events with a full re-enumeration every five years. Field agents capture plot data quarterly for the first three vintages.' },
  ]},
  { num:'5', title:'Quantification of GHG Emission Reductions and Removals', items:[
    { num:'5.4', title:'GHG Emission Reductions and Carbon Dioxide Removals', field_id:null, narrative:'Net carbon dioxide removals for monitoring period 1 are 1,120 tCO2e (Stratum A 640, Stratum B 180, Stratum C 300), quantified with the census-based approach in Section 8.3 of the methodology.' },
  ]},
];

/* ------ Documents a finding can be scoped to. Verra suffixes the title with the document ("Project Location – Monitoring Report"). ------
 * owner: who revises the document when a finding is raised against it. The VVB's own reports need no change request to the developer. */
const SCOPE_DOCS = {
  PD:                  { label:'Project Description', short:'PD',  owner:'developer', report:'validation report',   sections:'sections' },
  MR:                  { label:'Monitoring Report',   short:'MR',  owner:'developer', report:'verification report', sections:'mr_sections' },
  validation_report:   { label:'Validation Report',   short:'VR',  owner:'vvb',       report:'validation report',   sections:null },
  verification_report: { label:'Verification Report', short:'VER', owner:'vvb',       report:'verification report', sections:null },
};
function findingTitle(f) { const d = SCOPE_DOCS[f.scope_document]; return d ? `${f.title} – ${d.label}` : f.title; }
function sectionsForScope(review, scope) { const d = SCOPE_DOCS[scope]; return d && d.sections ? (review[d.sections] || []) : []; }
function sectionOfFinding(review, f) { return sectionsForScope(review, f.scope_document).flatMap(s => s.items).find(i => i.num === f.anchor.section) || null; }
function isDeveloperDocument(scope) { return (SCOPE_DOCS[scope] || SCOPE_DOCS.PD).owner === 'developer'; }

/* ------ Numbered evidence documents (cited by number, as Verra does) ------ */
const EVIDENCE_DOCS = [
  { id:'27', title:'Project boundary KML',                       filename:'ecogreen-boundary-v3.kml',          sha256:'a3f9c1…', uploaded_by:'Grace Kimani', date:'2026-11-12' },
  { id:'28', title:'Plot data export, Stratum B plots 43 to 46', filename:'stratum-b-plots-43-46.csv',          sha256:'7be204…', uploaded_by:'Grace Kimani', date:'2026-11-10' },
  { id:'31', title:'Stakeholder meeting invitations, 4 sub-counties', filename:'lsc-invitations-2024.pdf',      sha256:'0d41e8…', uploaded_by:'Grace Kimani', date:'2026-11-11' },
  { id:'32', title:'Attendance registers, 4 consultation meetings',  filename:'lsc-attendance-2024.pdf',       sha256:'c92f7a…', uploaded_by:'Grace Kimani', date:'2026-11-11' },
  { id:'33', title:'Consultation evaluation forms',             filename:'lsc-evaluation-forms-2024.pdf',      sha256:'5e6b30…', uploaded_by:'Grace Kimani', date:'2026-11-11' },
  { id:'34', title:'Planting units KML, monitoring period 1',    filename:'ecogreen-planting-units-mp1.kml',    sha256:'e17d4b…', uploaded_by:'Grace Kimani', date:'2026-11-13' },
];

/* ------ Field versions (the redline is computed between two of these) ------ */
const FIELD_VERSIONS = [
  // 1.13 Project Location (field: area)
  { id:'area@v1', field_id:'area', version:1, author:'Grace Kimani', date:'2026-03-14', reason:'Initial PD',
    value:'12,000 ha across 3 strata',
    narrative:'The project area covers 12,000 ha in Bungoma County, Kenya, centred on 0.5635 N, 34.5606 E. The boundary is defined by the KML file in document 27. Table 1, row 5 states the total eligible area as 12,000 ha.' },
  { id:'area@v2', field_id:'area', version:2, author:'Grace Kimani', date:'2026-10-02', reason:'Pre-submission check',
    value:'12,000 ha across 3 strata',
    narrative:'The project area covers 12,000 ha in Bungoma County, Kenya, centred on 0.5635 N, 34.5606 E. The boundary is defined by the KML file in document 27. Table 1, row 5 states the total eligible area as 12,000 ha.', hedera_anchor_id:'0.0.8321350@144' },
  { id:'area@v3', field_id:'area', version:3, author:'Grace Kimani', date:'2026-11-12', reason:'CR-01',
    value:'12,450 ha across 3 strata', evidence_doc_ids:['27'],
    narrative:'The project area covers 12,000 ha in Bungoma County, Kenya, centred on 0.5635 N, 34.5606 E. The boundary is defined by the KML file in document 27. Table 1, row 5 states the total eligible area as 12,450 ha.', hedera_anchor_id:'0.0.8321350@151' },
  // MR 1.8 Project Location (field: planting_units)
  { id:'planting_units@v1', field_id:'planting_units', version:1, author:'Joseph Mwangi', date:'2026-10-02', reason:'Initial MR',
    value:'1,840 planting units · 3 strata',
    narrative:'The project boundary is unchanged from the Project Description: 12,450 ha in Bungoma County, Kenya, defined by the KML in document 27. Planting units were established in all three strata inside the boundary during the monitoring period.', hedera_anchor_id:'0.0.8321350@145' },
  { id:'planting_units@v2', field_id:'planting_units', version:2, author:'Grace Kimani', date:'2026-11-13', reason:'CR-04',
    value:'1,840 planting units · 3 strata · KML in document 34', evidence_doc_ids:['34'],
    narrative:'The project boundary is unchanged from the Project Description: 12,450 ha in Bungoma County, Kenya, defined by the KML in document 27. Planting units were established in all three strata inside the boundary during the monitoring period. The georeferenced point of each of the 1,840 planting units is in document 34, a KML of the units established between 12 March 2025 and 11 March 2026, all inside the boundary in document 27.', hedera_anchor_id:'0.0.8321350@159' },
  // 4.1 Baseline Emissions (field: stratify)
  { id:'stratify@v1', field_id:'stratify', version:1, author:'Joseph Mwangi', date:'2026-03-12', reason:'Initial PD',
    value:'3 strata (lowland / mid / riparian)',
    narrative:'Baseline carbon stocks were estimated by stratum. Stratum A (lowland) 20 plots, Stratum B (riparian) 8 plots, Stratum C (mid-slope) 14 plots.' },
  { id:'stratify@v2', field_id:'stratify', version:2, author:'Grace Kimani', date:'2026-11-10', reason:'CR-02',
    value:'3 strata (lowland / mid / riparian) · 46 plots', evidence_doc_ids:['28'],
    narrative:'Baseline carbon stocks were estimated by stratum. Stratum A (lowland) 20 plots, Stratum B (riparian) 12 plots, Stratum C (mid-slope) 14 plots. Plot-level data are in document 28.', hedera_anchor_id:'0.0.8321350@149' },
  // 2.1.2 Stakeholder Consultation and Ongoing Communication (field: consent)
  { id:'consent@v1', field_id:'consent', version:1, author:'Grace Kimani', date:'2026-03-14', reason:'Initial PD',
    value:'Recorded in 4 sub-counties',
    narrative:'Local stakeholder consultations were held in each of the four sub-counties during 2024. Participants were informed of the project design, risks and benefits, and free, prior and informed consent was recorded.' },
  { id:'consent@v2', field_id:'consent', version:2, author:'Grace Kimani', date:'2026-11-11', reason:'CR-03',
    value:'Recorded in 4 sub-counties · evidence 31, 32, 33', evidence_doc_ids:['31','32','33'],
    narrative:'Local stakeholder consultations were held in each of the four sub-counties between June and September 2024. Invitations were issued two weeks in advance (document 31). Attendance registers for all four meetings are in document 32 and evaluation forms completed by participants are in document 33. Participants were informed of the project design, risks and benefits, and free, prior and informed consent was recorded.', hedera_anchor_id:'0.0.8321350@150' },
];

/* ------ Verified citation index (15 Oct 2026) ------
 * VCS Standard v4.7 (16 April 2024): Section 3 table of contents plus the
 * clauses read in full (3.1, 3.5, 3.11, 3.12, 3.18, 3.19).
 * VCS Project Description Template v4.4: every numbered heading.
 * VCS Monitoring Report Template v4.4: every numbered heading (read 15 Oct 2026
 * from the Word template's contents list and heading styles).
 * VM0047 v1.1: section index from the platform registry, full-text verified
 * 2026-05-19. A rule raised live against a section outside this index
 * renders the VERIFY tag. */
const _sub = (parent, n) => Array.from({ length:n }, (_, i) => `${parent}.${i+1}`);
const VERIFIED_SECTIONS = {
  'VCS Standard|v4.7': [ ..._sub('3', 26), ..._sub('3.1', 9), ..._sub('3.5', 9), ..._sub('3.11', 5), '3.12.1', ..._sub('3.18', 16), ..._sub('3.19', 29) ],
  'VCS Project Description Template|v4.4': [
    '1', ..._sub('1', 19), '1.4.1','1.4.2','1.4.3','1.5.1','1.16.1','1.16.2','1.16.3','1.17.1','1.17.2','1.17.3','1.19.1','1.19.2','1.19.3',
    '2', ..._sub('2', 4), ..._sub('2.1', 5), '2.2.1','2.2.2', ..._sub('2.3', 5), '2.4.1','2.4.2','2.4.3',
    '3', ..._sub('3', 6), '3.5.1','3.5.2',
    '4', ..._sub('4', 4),
    '5', ..._sub('5', 3) ],
  'VCS Monitoring Report Template|v4.4': [
    '1', ..._sub('1', 13), '1.10.1','1.10.2','1.11.1','1.11.2','1.11.3',
    '2', ..._sub('2', 4), ..._sub('2.1', 5), '2.2.1','2.2.2', ..._sub('2.3', 5), '2.4.1','2.4.2','2.4.3',
    '3', ..._sub('3', 4), '3.2.1','3.2.2',
    '4', ..._sub('4', 3),
    '5', ..._sub('5', 4) ],
  'VM0047|v1.1': [ '1','1.1','1.2','2','3','4','4.1','4.2','4.3','4.4','5','5.1','5.2','5.3','6','6.1','6.2','7','7.1','7.2','7.3',
    '8','8.1','8.1.1','8.1.2','8.2','8.3','8.4','8.5','8.5.1','8.5.2','8.6','8.7','9','9.1','9.2','9.3','9.3.1','10' ],
};
function isVerifiedCitation(rule) {
  const list = VERIFIED_SECTIONS[`${rule.standard}|${rule.version}`];
  return !!list && list.includes(String(rule.section || '').trim());
}

/* ------ Standard "action required" trio Verra uses on nearly every finding ------ */
const STANDARD_ACTIONS = (section, confirmText, scope = 'PD') => {
  const d = SCOPE_DOCS[scope] || SCOPE_DOCS.PD;
  return [
    { n:1, owner:'vvb', text:`The VVB must ensure the project proponent updates Section ${section} of the ${d.label} accordingly.` },
    { n:2, owner:'vvb', text: confirmText },
    { n:3, owner:'vvb', text:`The VVB must provide an independent assessment of the updates and update the relevant sections of the ${d.report}.` },
  ];
};

/* ------ Findings ------ */
const REVIEW_FINDINGS = [
  {
    id:'RR-01', number:1, title:'Project Location',
    layer:'registry_to_vvb', review_type:'validation', scope_document:'PD',
    anchor:{ section:'1.13', section_title:'Project Location', field_id:'area', row:5, column:2, quote:'12,000 ha' },
    issue:[
      { n:1, text:'Section 1.13 paragraph 1 states a project area of 12,000 ha. Table 1, row 5, column 2 states 12,000 ha. The boundary file submitted as document 27 encloses 12,450 ha.' },
      { n:2, text:'The eligible area used in Section 4.1 for baseline stock estimation is 12,450 ha. The Project Description is internally inconsistent.' },
    ],
    actions_required: STANDARD_ACTIONS('1.13', 'The VVB must confirm the total eligible area against the geographic boundary file and ensure the same value is used in every section of the Project Description.'),
    program_rules:[ { standard:'VCS Standard', version:'v4.7', section:'3.11.2' }, { standard:'VCS Project Description Template', version:'v4.4', section:'1.13' } ],
    severity:null,
    raised_by:{ role:'registry', name:'Priya Nair', org:'Verra', date:'2026-11-06' },
    status:'pending_vvb',
    rounds:[
      {
        n:1,
        change_request:{ id:'CR-01', due_days:10, date:'2026-11-07', note:'Confirm the hectares against the KML (document 27) and update Table 1 row 5 in Section 1.13.',
          developer_handback:{ field_version_id:'area@v3', evidence_doc_ids:['27'], note:'Row 5 corrected to 12,450 ha from the KML export.', date:'2026-11-12' } },
        vvb_response:{
          text:'Section 1.13 Table 1 row 5 updated to 12,450 ha. VVB validated the value against document 27_Project boundary KML by recomputing the enclosed area. Validation report Section 3.2 updated.',
          author:'Sarah Chen', date:'2026-11-18', evidence_doc_ids:['27'], field_version_ids:['area@v3'], report_section_updated:'Validation report §3.2' },
        registry_response:{
          // Per-item outcomes, as in Verra 3197 findings 7 and 9: item 2 closes, item 1 stays open, the finding stays open.
          items:[
            { n:1, outcome:'open',   text:'Table 1 row 5 now states 12,450 ha. Section 1.13 paragraph 1 still reads 12,000 ha. The issue is open.' },
            { n:2, outcome:'closed', text:'Section 4.1 uses 12,450 ha, which now matches Table 1 row 5 and the boundary file. The issue is closed.' },
          ],
          author:'Priya Nair', date:'2026-11-24', outcome:'open', follow_up_ask:'Reconcile Section 1.13 paragraph 1 with Table 1 row 5.' },
      },
      { n:2 },
    ],
    hedera_anchor_ids:['0.0.8321350@147','0.0.8321350@153','0.0.8321350@156'],
  },
  {
    id:'RR-02', number:2, title:'Baseline sampling in Stratum B',
    layer:'registry_to_vvb', review_type:'validation', scope_document:'PD',
    anchor:{ section:'4.1', section_title:'Baseline Emissions', field_id:'stratify', quote:'Stratum B (riparian) 8 plots' },
    issue:[
      { n:1, text:'Section 4.1 reports 8 sample plots in Stratum B (riparian). The methodology quantifies sampling uncertainty from the standard error of the plot sample (VM0047 Section 8.5.1) and requires the sampling intensity to be justified in the monitoring plan (Section 9.3); the Project Description does not demonstrate that 8 plots meet the targeted precision.' },
    ],
    actions_required: STANDARD_ACTIONS('4.1', 'The VVB must confirm the sample size per stratum meets the methodology requirement and that plot-level data are available for all plots.'),
    program_rules:[ { standard:'VM0047', version:'v1.1', section:'8.5.1' }, { standard:'VM0047', version:'v1.1', section:'9.3' } ],
    severity:null,
    raised_by:{ role:'registry', name:'Priya Nair', org:'Verra', date:'2026-11-06' },
    status:'closed',
    rounds:[
      {
        n:1,
        change_request:{ id:'CR-02', due_days:10, date:'2026-11-07', note:'Add Stratum B plots to reach the minimum and attach the plot export.',
          developer_handback:{ field_version_id:'stratify@v2', evidence_doc_ids:['28'], note:'Four additional riparian plots (43 to 46) captured by the field team and exported.', date:'2026-11-10' } },
        vvb_response:{
          text:'Section 4.1 updated: Stratum B now has 12 plots. VVB validated plots 43 to 46 against document 28_Plot data export by desk review of GPS, DBH and photo records, and by onsite re-measurement of plots 43 and 45. Validation report Section 4.3 updated.',
          author:'Sarah Chen', date:'2026-11-18', evidence_doc_ids:['28'], field_version_ids:['stratify@v2'], report_section_updated:'Validation report §4.3' },
        registry_response:{ text:'The sample size per stratum is now demonstrated and plot-level data are available. The issue is closed.', author:'Priya Nair', date:'2026-11-24', outcome:'closed' },
      },
    ],
    hedera_anchor_ids:['0.0.8321350@148','0.0.8321350@152','0.0.8321350@157'],
  },
  {
    id:'RR-03', number:3, title:'Stakeholder Consultation',
    layer:'registry_to_vvb', review_type:'validation', scope_document:'PD',
    anchor:{ section:'2.1.2', section_title:'Stakeholder Consultation and Ongoing Communication', field_id:'consent', quote:'consultations were held in each of the four sub-counties' },
    issue:[
      { n:1, text:'Section 2.1.2 states that consultations were held but provides no evidence of how stakeholders were invited, who attended, or how their input was evaluated.' },
    ],
    actions_required: STANDARD_ACTIONS('2.1.2', 'The VVB must confirm that invitations, attendance records and evaluation of stakeholder input are documented for each consultation.'),
    program_rules:[ { standard:'VCS Standard', version:'v4.7', section:'3.18.2' }, { standard:'VCS Standard', version:'v4.7', section:'3.18.3' } ],
    severity:null,
    raised_by:{ role:'registry', name:'Priya Nair', org:'Verra', date:'2026-11-06' },
    status:'closed',
    rounds:[
      {
        n:1,
        change_request:{ id:'CR-03', due_days:10, date:'2026-11-07', note:'Attach invitations, attendance registers and evaluation forms for the four consultation meetings.',
          developer_handback:{ field_version_id:'consent@v2', evidence_doc_ids:['31','32','33'], note:'Three evidence documents uploaded and Section 2.1.2 expanded.', date:'2026-11-11' } },
        vvb_response:{
          text:'Section 2.1.2 expanded with dates, invitation process and evaluation. VVB validated documents 31_Stakeholder meeting invitations, 32_Attendance registers and 33_Consultation evaluation forms by desk review and by onsite interview with participants in two sub-counties. Validation report Section 3.5 updated.',
          author:'Sarah Chen', date:'2026-11-18', evidence_doc_ids:['31','32','33'], field_version_ids:['consent@v2'], report_section_updated:'Validation report §3.5' },
        registry_response:{ text:'The consultation process is now documented. The issue is closed.', author:'Priya Nair', date:'2026-11-24', outcome:'closed' },
      },
    ],
    hedera_anchor_ids:['0.0.8321350@146','0.0.8321350@154','0.0.8321350@158'],
  },
  /* ---- Monitoring Report scope (Verra 3197 finding 10: no spatial file of where the activity was implemented). Combined validation and first verification. ---- */
  {
    id:'RR-04', number:4, title:'Project Location',
    layer:'registry_to_vvb', review_type:'verification', scope_document:'MR',
    anchor:{ section:'1.8', section_title:'Project Location', field_id:'planting_units', quote:'Planting units were established in all three strata inside the boundary' },
    issue:[
      { n:1, text:'Section 1.8 of the Monitoring Report restates the project boundary from the Project Description but does not include a geodetic file showing where the planting units were established within the boundary during the monitoring period (12 March 2025 to 11 March 2026).' },
    ],
    actions_required:[
      { n:1, owner:'vvb', text:'The VVB must submit a KML file of the planting units implemented within the project boundary during the monitoring period.' },
      { n:2, owner:'vvb', text:'The VVB must confirm that every planting unit recorded in Section 4.2 of the Monitoring Report lies inside the boundary in document 27.' },
      { n:3, owner:'vvb', text:'The VVB must provide an independent assessment of the updates and update the relevant sections of the verification report.' },
    ],
    program_rules:[ { standard:'VCS Standard', version:'v4.7', section:'3.11.2' }, { standard:'VM0047', version:'v1.1', section:'9.2' } ],
    severity:null,
    raised_by:{ role:'registry', name:'Priya Nair', org:'Verra', date:'2026-11-06' },
    status:'pending_registry',
    rounds:[
      {
        n:1,
        change_request:{ id:'CR-04', due_days:10, date:'2026-11-07', note:'Export the planting-unit KML for monitoring period 1 from the field-agent records and attach it to Monitoring Report Section 1.8.',
          developer_handback:{ field_version_id:'planting_units@v2', evidence_doc_ids:['34'], note:'KML of all 1,840 planting units exported from the field records and attached as document 34. Section 1.8 now cites it.', date:'2026-11-13' } },
        vvb_response:{
          text:'Monitoring Report Section 1.8 updated and the planting-unit KML for monitoring period 1 submitted as document 34_Planting units KML. VVB confirmed by GIS overlay that all 1,840 units lie inside the boundary in document 27, and re-located 40 units on site during the verification visit. Verification report Section 3.1 updated.',
          author:'Sarah Chen', date:'2026-11-18', evidence_doc_ids:['34','27'], field_version_ids:['planting_units@v2'], report_section_updated:'Verification report §3.1' },
      },
    ],
    hedera_anchor_ids:['0.0.8321350@145','0.0.8321350@160'],
  },
  /* ---- Validation Report scope (Verra 3197 findings 15 and 16: the VVB's own report disagrees with the PD). No change request to the developer; the VVB corrects its report and responds. ---- */
  {
    id:'RR-05', number:5, title:'Project start date and household count',
    layer:'registry_to_vvb', review_type:'validation', scope_document:'validation_report',
    anchor:{ section:'3.2', section_title:'Validation report Section 3.2', field_id:null, quote:'14 March 2025' },
    issue:[
      { n:1, text:'Section 3.2 of the validation report, in the revision submitted on 18 November 2026, states that the project activity started on 14 March 2025 and that 1,790 households were enrolled at the time of the site visit. Section 1.9 of the Project Description states a start date of 12 March 2025 and Section 1.1 states 1,840 households. The validation report and the Project Description are inconsistent.' },
    ],
    actions_required:[
      { n:1, owner:'vvb', text:'The VVB must clarify the inconsistency between the validation report and the Project Description on the project start date and the number of households, and state which value it validated.' },
      { n:2, owner:'vvb', text:'The VVB must provide an independent assessment of the updates and update the relevant sections of the validation report.' },
    ],
    program_rules:[ { standard:'VCS Standard', version:'v4.7', section:'3.5.1' } ],
    severity:null,
    raised_by:{ role:'registry', name:'Priya Nair', org:'Verra', date:'2026-11-24' },
    status:'pending_vvb',
    rounds:[ { n:1 } ],
    hedera_anchor_ids:['0.0.8321350@161'],
  },
  /* ---- Layer 1: the three existing VVB findings, migrated into the same shape ---- */
  {
    id:'CAR-01', number:1, title:'Stratum B baseline samples below minimum',
    layer:'vvb_to_developer', review_type:'validation', scope_document:'PD',
    anchor:{ section:'4.1', section_title:'Baseline Emissions', field_id:'stratify' },
    issue:[ { n:1, text:'Only 8 plots sampled in Stratum B (riparian). Either expand sampling or merge Stratum B into Stratum A with statistical justification.' } ],
    actions_required:[ { n:1, owner:'developer', text:'Expand Stratum B sampling to the methodology minimum or justify a merged stratum.' } ],
    program_rules:[ { standard:'VM0047', version:'v1.1', section:'8.5.1' } ],
    severity:'major',
    raised_by:{ role:'vvb', name:'Sarah Chen', org:'SCS Global Services', date:'2026-10-14' },
    status:'closed',
    rounds:[ { n:1, change_request:{ id:'CR-CAR-01', due_days:14, date:'2026-10-14', note:'Corrective action: bring Stratum B to the minimum sample size.',
      developer_handback:{ field_version_id:'stratify@v2', evidence_doc_ids:['28'], note:'Plots 43 to 46 added.', date:'2026-11-10' } },
      vvb_response:{ text:'Corrective action verified. Closed.', author:'Sarah Chen', date:'2026-11-12', evidence_doc_ids:['28'], field_version_ids:['stratify@v2'], report_section_updated:'Validation report §4.3' } } ],
    hedera_anchor_ids:['0.0.8321350@133'],
  },
  {
    id:'CL-01', number:2, title:'Plot 42 outlier: confirm or exclude',
    layer:'vvb_to_developer', review_type:'validation', scope_document:'PD',
    anchor:{ section:'4.1', section_title:'Baseline Emissions', field_id:'plot42' },
    issue:[ { n:1, text:'DBH 84 cm is 5 standard deviations above the plot mean. Field re-measurement or written justification is needed before validation can proceed.' } ],
    actions_required:[ { n:1, owner:'developer', text:'Re-measure plot 42 or provide written justification.' } ],
    program_rules:[ { standard:'VM0047', version:'v1.1', section:'9.3' } ],
    severity:'minor',
    raised_by:{ role:'vvb', name:'Sarah Chen', org:'SCS Global Services', date:'2026-10-14' },
    status:'pending_developer',
    rounds:[ { n:1, change_request:{ id:'CR-CL-01', due_days:7, date:'2026-10-14', note:'Clarification: confirm the plot 42 DBH reading or exclude the plot with justification.' } } ],
    hedera_anchor_ids:['0.0.8321350@133'],
  },
  {
    id:'FAR-01', number:3, title:'Tenure documentation for the leakage belt',
    layer:'vvb_to_developer', review_type:'validation', scope_document:'PD',
    anchor:{ section:'2.3.4', section_title:'Property Rights', field_id:'tenure' },
    issue:[ { n:1, text:'No customary or statutory tenure record is uploaded for the 412 ha leakage belt. Recommended before the site visit.' } ],
    actions_required:[ { n:1, owner:'developer', text:'Upload tenure records for the leakage belt before the first verification.' } ],
    program_rules:[ { standard:'VCS Standard', version:'v4.7', section:'3.19.19' } ],
    severity:'observation',
    raised_by:{ role:'vvb', name:'Sarah Chen', org:'SCS Global Services', date:'2026-10-13' },
    status:'pending_developer',
    rounds:[ { n:1, change_request:{ id:'CR-FAR-01', due_days:null, date:'2026-10-13', note:'Forward action: tenure records to be in place before the first verification.' } } ],
    hedera_anchor_ids:['0.0.8321350@128'],
  },
];

/* ------ VVB comments on sections: to the developer, or private working notes ------ */
const COMMENTS = [
  { id:'CM-01', doc:'PD', section:'1.13', field_id:'area', author:'Sarah Chen', role:'vvb', audience:'developer', date:'2026-11-07',
    text:'Grace, when you update Table 1 row 5 please check the paragraph 1 figure as well. The registry reads both and will compare them.' },
  { id:'CM-02', doc:'PD', section:'4.1', field_id:'stratify', author:'Sarah Chen', role:'vvb', audience:'private', date:'2026-11-08',
    text:'Desk review: plots 43 to 46 GPS fall inside the Stratum B polygon. Re-measure 43 and 45 on the site visit before closing CAR-01.' },
];
const VVB_KINDS = {
  CAR: { label:'Corrective action request', severity:'major',       dueDays:14, hint:'A nonconformity that must be corrected before validation can conclude.' },
  CL:  { label:'Clarification request',     severity:'minor',       dueDays:7,  hint:'Information that is unclear or insufficient to reach a conclusion.' },
  FAR: { label:'Forward action request',    severity:'observation', dueDays:null, hint:'A matter to be addressed before the next verification, not a stop to validation.' },
};

/* ------ Report header, filled from the project record ------ */
const REVIEW_REPORT = {
  template:'Project Review Report template v4.2',
  project_id:'PRJ-KE-BUS001', registry_project_id:'Pending pipeline listing',
  project_name:'Pamoja EcoGreen Bamboo',
  review_type:'Validation and Verification', programs:['VCS'],
  monitoring_period:'12 March 2025 to 11 March 2026',
  proponent:'Pamoja EcoGreen Co-operative',
  vvb:'SCS Global Services',
  assessment_criteria:'VCS Standard v4.7; VM0047 v1.1',
  date_first_issue:'2026-11-06', date_second_issue:'2026-11-24', date_final_issue:null,
  conclusion:null,
  issues:[ { n:1, date:'2026-11-06', by:'Priya Nair' }, { n:2, date:'2026-11-24', by:'Priya Nair' } ],
};

/* ------ Seat personas ------ */
const SEATS = {
  registry:  { id:'registry',  name:'Priya Nair',   initials:'PN', org:'Verra',                 role:'Registry Reviewer', subtitle:'Verra Certification', accent:'#0077B6' },
  vvb:       { id:'vvb',       name:'Sarah Chen',   initials:'SC', org:'SCS Global Services',   role:'VVB Auditor',       subtitle:'SCS Global · VVB-007', accent:'#2BC48A' },
  developer: { id:'developer', name:'Grace Kimani', initials:'GK', org:'Pamoja EcoGreen Co-operative', role:'Project Developer', subtitle:'Pamoja EcoGreen Co-op', accent:'#F4C300' },
};

const STATUS_META = {
  raised:            { label:'Raised',            tone:'blue' },
  pending_vvb:       { label:'Pending VVB',       tone:'amber' },
  pending_developer: { label:'Pending developer', tone:'amber' },
  pending_registry:  { label:'Pending registry',  tone:'blue' },
  closed:            { label:'Closed',            tone:'green' },
};

/* ------ Date helpers (the review runs on absolute dates, Nov 2026) ------ */
let REVIEW_CLOCK = new Date('2026-11-25T09:00:00Z');
function reviewToday() { return REVIEW_CLOCK.toISOString().slice(0,10); }
function reviewTick(days) { REVIEW_CLOCK = new Date(REVIEW_CLOCK.getTime() + days*86400000); return reviewToday(); }
function fmtDate(iso) {
  if (!iso) return '—';
  const d = new Date(iso + 'T00:00:00Z');
  return d.toLocaleDateString('en-GB', { day:'numeric', month:'short', year:'numeric', timeZone:'UTC' });
}

/* ------ Hedera sequence helper (keeps HEDERA_EVENTS telling the same story) ------ */
let HEDERA_SEQ = 161;
function anchor(actor, action, kind) {
  HEDERA_SEQ += 1;
  const id = `0.0.8321350@${HEDERA_SEQ}`;
  if (window.HEDERA_EVENTS) window.HEDERA_EVENTS.unshift({ t: fmtDate(reviewToday()), actor, action, tx:id, kind });
  return id;
}

/* ------ Word-level diff (LCS over tokens) for the redline ------ */
function wordDiff(a, b) {
  const A = (a || '').split(/(\s+)/).filter(s => s.length), B = (b || '').split(/(\s+)/).filter(s => s.length);
  const n = A.length, m = B.length;
  const L = Array.from({ length:n+1 }, () => new Array(m+1).fill(0));
  for (let i=n-1;i>=0;i--) for (let j=m-1;j>=0;j--) L[i][j] = A[i]===B[j] ? L[i+1][j+1]+1 : Math.max(L[i+1][j], L[i][j+1]);
  const out = []; let i=0, j=0;
  const push = (type, text) => { const last = out[out.length-1]; if (last && last.type===type) last.text += text; else out.push({ type, text }); };
  while (i<n && j<m) {
    if (A[i]===B[j]) { push('same', A[i]); i++; j++; }
    else if (L[i+1][j] >= L[i][j+1]) { push('del', A[i]); i++; }
    else { push('ins', B[j]); j++; }
  }
  while (i<n) { push('del', A[i++]); }
  while (j<m) { push('ins', B[j++]); }
  return out;
}

/* ------ Selectors ------ */
function latestVersion(versions, fieldId) {
  return versions.filter(v => v.field_id === fieldId).sort((a,b) => b.version - a.version)[0] || null;
}
function versionById(versions, id) { return versions.find(v => v.id === id) || null; }
function currentRound(f) { return f.rounds[f.rounds.length - 1]; }
function sectionFor(fieldId) {
  for (const s of [...PD_SECTIONS, ...MR_SECTIONS]) for (const it of s.items) if (it.field_id === fieldId) return it;
  return null;
}
/* Per-item outcomes. A registry response with items[] closes or keeps open each issue item; the finding's
 * outcome is open while any item is open. A response without items[] applies its outcome to every item. */
function responseItems(rr) { return rr && rr.items && rr.items.length ? rr.items : null; }
function deriveOutcome(items) { return items.some(i => i.outcome === 'open') ? 'open' : 'closed'; }
function itemOutcome(finding, n) {
  for (const r of finding.rounds) {
    const rr = r.registry_response; if (!rr) continue;
    const items = responseItems(rr);
    if (items) { const it = items.find(i => i.n === n); if (it && it.outcome === 'closed') return { state:'closed', round:r.n }; }
    else if (rr.outcome === 'closed') return { state:'closed', round:r.n };
  }
  return { state: finding.status === 'closed' ? 'closed' : 'open', round:null };
}
function openIssueItems(finding) { return finding.issue.filter(it => itemOutcome(finding, it.n).state === 'open'); }
function roundOutcomeLabel(rr) {
  const items = responseItems(rr);
  if (!items) return rr.outcome === 'closed' ? 'Closed' : 'Kept open';
  const closed = items.filter(i => i.outcome === 'closed').length, open = items.length - closed;
  if (!open) return 'Closed'; if (!closed) return 'Kept open';
  return `${closed} closed · ${open} open`;
}
/* The version the registry last saw for a finding: the one cited in the most recent sent VVB response, else the version before the first change. */
function baselineVersionFor(review, f) {
  const sent = f.rounds.filter(r => r.vvb_response).map(r => r.vvb_response.field_version_ids && r.vvb_response.field_version_ids[0]).filter(Boolean);
  if (sent.length) return versionById(review.versions, sent[sent.length-1]);
  const all = review.versions.filter(v => v.field_id === f.anchor.field_id).sort((a,b)=>a.version-b.version);
  // The version in force when the finding was raised: the latest one dated before raise date.
  const before = all.filter(v => v.date <= f.raised_by.date);
  return before[before.length-1] || all[0] || null;
}

/* ------ Pure transitions. Each returns a new review state. ------ */
const reviewActions = {
  openChangeRequest(review, { findingId, note, dueDays }) {
    const findings = review.findings.map(f => {
      if (f.id !== findingId) return f;
      const rounds = f.rounds.slice();
      const r = { ...rounds[rounds.length-1] };
      const n = review.findings.filter(x => x.layer === 'registry_to_vvb').reduce((acc, x) => acc + x.rounds.filter(rr => rr.change_request).length, 0) + 1;
      r.change_request = { id:`CR-${String(n).padStart(2,'0')}`, due_days: dueDays, date: reviewToday(), note };
      rounds[rounds.length-1] = r;
      return { ...f, rounds, status:'pending_developer', hedera_anchor_ids:[...f.hedera_anchor_ids, anchor('Sarah C. (VVB)', `opened change request ${r.change_request.id} on ${f.id}`, 'finding')] };
    });
    return { ...review, findings };
  },
  handBack(review, { findingId, narrative, value, evidenceDocIds, note }) {
    const f = review.findings.find(x => x.id === findingId);
    const prev = latestVersion(review.versions, f.anchor.field_id);
    const version = {
      id:`${f.anchor.field_id}@v${(prev ? prev.version : 0) + 1}`, field_id:f.anchor.field_id, version:(prev ? prev.version : 0) + 1,
      author:'Grace Kimani', date:reviewToday(), reason:currentRound(f).change_request.id,
      value: value != null ? value : (prev ? prev.value : ''), narrative, evidence_doc_ids:evidenceDocIds,
      hedera_anchor_id: anchor('Grace K.', `saved ${f.anchor.field_id} v${(prev ? prev.version : 0) + 1} for ${currentRound(f).change_request.id}`, 'confirm'),
    };
    const findings = review.findings.map(x => {
      if (x.id !== findingId) return x;
      const rounds = x.rounds.slice();
      const r = { ...rounds[rounds.length-1] };
      r.change_request = { ...r.change_request, developer_handback:{ field_version_id:version.id, evidence_doc_ids:evidenceDocIds, note, date:reviewToday() } };
      rounds[rounds.length-1] = r;
      return { ...x, rounds, status:'pending_vvb' };
    });
    return { ...review, findings, versions:[...review.versions, version] };
  },
  addEvidence(review, { title, filename }) {
    const maxId = review.evidence.reduce((m, d) => Math.max(m, parseInt(d.id, 10)), 0);
    const doc = { id:String(maxId + 1), title, filename, sha256: Math.random().toString(16).slice(2,8) + '…', uploaded_by:'Grace Kimani', date:reviewToday() };
    return { ...review, evidence:[...review.evidence, doc], _lastDoc: doc.id };
  },
  sendVvbResponse(review, { findingId, text, evidenceDocIds, reportSection }) {
    const findings = review.findings.map(f => {
      if (f.id !== findingId) return f;
      const rounds = f.rounds.slice();
      const r = { ...rounds[rounds.length-1] };
      const hb = r.change_request && r.change_request.developer_handback;
      r.vvb_response = { text, author:'Sarah Chen', date:reviewToday(), evidence_doc_ids:evidenceDocIds, field_version_ids: hb ? [hb.field_version_id] : [], report_section_updated:reportSection };
      rounds[rounds.length-1] = r;
      const isLayer1 = f.layer === 'vvb_to_developer';
      return { ...f, rounds, status: isLayer1 ? 'closed' : 'pending_registry', hedera_anchor_ids:[...f.hedera_anchor_ids, anchor('Sarah C. (VVB)', `sent round ${r.n} response on ${f.id}`, 'finding')] };
    });
    return { ...review, findings };
  },
  sendRegistryResponse(review, { findingId, text, outcome, followUpAsk, items }) {
    const findings = review.findings.map(f => {
      if (f.id !== findingId) return f;
      const rounds = f.rounds.slice();
      const r = { ...rounds[rounds.length-1] };
      if (items && items.length) outcome = deriveOutcome(items);
      r.registry_response = { text, items: items && items.length ? items : undefined, author:'Priya Nair', date:reviewToday(), outcome, follow_up_ask: outcome === 'open' ? followUpAsk : undefined };
      rounds[rounds.length-1] = r;
      if (outcome === 'open') rounds.push({ n: r.n + 1 });
      return { ...f, rounds, status: outcome === 'closed' ? 'closed' : 'pending_vvb', hedera_anchor_ids:[...f.hedera_anchor_ids, anchor('Verra', `${outcome === 'closed' ? 'closed' : 'kept open'} ${f.id} in round ${r.n}`, 'finding')] };
    });
    return { ...review, findings };
  },
  raiseFinding(review, { title, section, field_id, quote, issue, actions, rule, scope_document }) {
    const scope = SCOPE_DOCS[scope_document] ? scope_document : 'PD';
    const regCount = review.findings.filter(f => f.layer === 'registry_to_vvb').length + 1;
    const sec = sectionsForScope(review, scope).flatMap(s => s.items).find(it => it.num === section);
    const f = {
      id:`RR-${String(regCount).padStart(2,'0')}`, number:regCount, title: (title || (sec ? sec.title : 'Section ' + section)).replace(/\s+–\s+.*$/, ''),
      layer:'registry_to_vvb', review_type: scope === 'MR' || scope === 'verification_report' ? 'verification' : 'validation', scope_document:scope,
      anchor:{ section, section_title: sec ? sec.title : '', field_id: field_id || (sec ? sec.field_id : null), quote },
      issue: issue.map((t, i) => ({ n:i+1, text:t })),
      actions_required: actions && actions.length ? actions.map((t,i)=>({ n:i+1, owner:'vvb', text:t })) : STANDARD_ACTIONS(section, 'The VVB must confirm the corrected information against supporting evidence.', scope),
      program_rules: rule ? [ { ...rule, verify: !isVerifiedCitation(rule) } ] : [],
      severity:null, raised_by:{ role:'registry', name:'Priya Nair', org:'Verra', date:reviewToday() },
      status:'pending_vvb', rounds:[ { n:1 } ],
      hedera_anchor_ids:[ anchor('Verra', `raised finding RR-${String(regCount).padStart(2,'0')} on ${SCOPE_DOCS[scope].short} §${section}`, 'finding') ],
    };
    return { ...review, findings:[...review.findings, f] };
  },
  raiseVvbFinding(review, { kind, title, section, field_id, quote, issue, dueDays, note, rule, scope_document }) {
    const scope = SCOPE_DOCS[scope_document] ? scope_document : 'PD';
    const k = VVB_KINDS[kind] ? kind : 'CAR';
    const nth = review.findings.filter(f => f.layer === 'vvb_to_developer' && f.id.startsWith(k + '-')).length + 1;
    const id = `${k}-${String(nth).padStart(2,'0')}`;
    const number = review.findings.filter(f => f.layer === 'vvb_to_developer').length + 1;
    const sec = sectionsForScope(review, scope).flatMap(s => s.items).find(it => it.num === section);
    const f = {
      id, number, title: (title || (sec ? sec.title : 'Section ' + section)).replace(/\s+–\s+.*$/, ''),
      layer:'vvb_to_developer', review_type: scope === 'MR' ? 'verification' : 'validation', scope_document:scope,
      anchor:{ section, section_title: sec ? sec.title : '', field_id: field_id || (sec ? sec.field_id : null), quote },
      issue: issue.map((t, i) => ({ n:i+1, text:t })),
      actions_required:[ { n:1, owner:'developer', text: note || `Update Section ${section} of the ${SCOPE_DOCS[scope].label} and attach supporting evidence.` } ],
      program_rules: rule ? [ { ...rule, verify: !isVerifiedCitation(rule) } ] : [],
      severity: VVB_KINDS[k].severity,
      raised_by:{ role:'vvb', name:'Sarah Chen', org:'SCS Global Services', date:reviewToday() },
      status:'pending_developer',
      rounds:[ { n:1, change_request:{ id:`CR-${id}`, due_days: dueDays == null ? VVB_KINDS[k].dueDays : dueDays, date:reviewToday(), note: note || '' } } ],
      hedera_anchor_ids:[ anchor('Sarah C. (VVB)', `raised ${id} on ${SCOPE_DOCS[scope].short} §${section}`, 'finding') ],
    };
    return { ...review, findings:[...review.findings, f] };
  },
  addComment(review, { doc, section, field_id, audience, text }) {
    const id = `CM-${String((review.comments || []).length + 1).padStart(2,'0')}`;
    const c = { id, doc, section, field_id: field_id || null, author:'Sarah Chen', role:'vvb', audience: audience === 'private' ? 'private' : 'developer', date:reviewToday(), text };
    anchor('Sarah C. (VVB)', `${c.audience === 'private' ? 'noted' : 'commented'} on ${doc} §${section}`, 'confirm');
    return { ...review, comments:[...(review.comments || []), c] };
  },
  issueReport(review, { kind }) {
    const open = review.findings.filter(f => f.layer === 'registry_to_vvb' && f.status !== 'closed').length;
    const report = { ...review.report };
    const today = reviewToday();
    if (kind === 'final') { report.date_final_issue = today; report.conclusion = open === 0 ? 'Approved' : 'Not approved'; }
    report.issues = [...report.issues, { n: report.issues.length + 1, date: today, by:'Priya Nair', kind }];
    anchor('Verra', `issued Project Review Report (${kind})`, 'commit');
    return { ...review, report };
  },
  advanceClock(review, { days }) { reviewTick(days); return { ...review, _clock: reviewToday() }; },
};

const REVIEW_SEED = {
  findings: REVIEW_FINDINGS,
  versions: FIELD_VERSIONS,
  evidence: EVIDENCE_DOCS,
  report: REVIEW_REPORT,
  sections: PD_SECTIONS,
  mr_sections: MR_SECTIONS,
  comments: COMMENTS,
  _clock: reviewToday(),
};

window.PD_SECTIONS = PD_SECTIONS;
window.MR_SECTIONS = MR_SECTIONS;
window.SCOPE_DOCS = SCOPE_DOCS;
window.findingTitle = findingTitle;
window.sectionsForScope = sectionsForScope;
window.sectionOfFinding = sectionOfFinding;
window.isDeveloperDocument = isDeveloperDocument;
window.responseItems = responseItems;
window.itemOutcome = itemOutcome;
window.openIssueItems = openIssueItems;
window.roundOutcomeLabel = roundOutcomeLabel;
window.EVIDENCE_DOCS = EVIDENCE_DOCS;
window.COMMENTS = COMMENTS;
window.VVB_KINDS = VVB_KINDS;
window.FIELD_VERSIONS = FIELD_VERSIONS;
window.REVIEW_FINDINGS = REVIEW_FINDINGS;
window.REVIEW_REPORT = REVIEW_REPORT;
window.REVIEW_SEED = REVIEW_SEED;
window.SEATS = SEATS;
window.STATUS_META = STATUS_META;
window.reviewActions = reviewActions;
window.wordDiff = wordDiff;
window.latestVersion = latestVersion;
window.versionById = versionById;
window.currentRound = currentRound;
window.sectionFor = sectionFor;
window.baselineVersionFor = baselineVersionFor;
window.fmtDate = fmtDate;
window.reviewToday = reviewToday;
