/* ================================================================
 * Registry reviewer seat (Verra).
 *   1. RegistryQueue     — projects awaiting review
 *   2. RegistryPD        — project documents by section (Project
 *                          Description and Monitoring Report tabs),
 *                          raise a finding against a section
 *   3. RegistryFindings  — list + ReviewThread
 *   4. RegistryReport    — Project Review Report in the template v4.2
 *                          layout, downloaded as a PDF file
 * The registry never sees change requests and never addresses the
 * project developer. Those rules live in ReviewThread (seat='registry').
 * ================================================================ */

function RegistryQueue({ review, hero, onOpenProject, onOpenView }) {
  const reg = review.findings.filter(f => f.layer === 'registry_to_vvb');
  const open = reg.filter(f => f.status !== 'closed');
  const due = reg.filter(f => f.status === 'pending_registry');
  const rows = [
    { id:hero.id, name:hero.name, proponent:'Pamoja EcoGreen Co-operative', vvb:'SCS Global Services', methodology:'VM0047 v1.1', review:review.report.review_type, days:19, open:open.length, due:due.length, round:Math.max(...reg.map(f=>currentRound(f).n)), active:true },
    { id:'PRJ-UG-KMP003', name:'Kampala Urban Agroforestry', proponent:'Pamoja East Africa Ltd', vvb:'Not yet appointed', methodology:'AR-ACM0003 v2.0', review:'Pipeline listing', days:4, open:0, due:0, round:0 },
    { id:'PRJ-RW-BUG005', name:'Bugesera Cookstoves', proponent:'Rwanda Clean Cooking Co-op', vvb:'Not yet appointed', methodology:'VM0050 v1.0', review:'Pipeline listing', days:2, open:0, due:0, round:0 },
  ];
  return (
    <main style={{flex:1, padding:'28px 32px', background:RV.bg, minWidth:0}}>
      <ReviewPageHeader eyebrow="Verra Certification · Review queue" title="Projects in review"
        body="Each row is a project submitted through Pamoja. Findings are raised section by section against the Project Description, the Monitoring Report, or the VVB's own validation and verification reports. The VVB responds, and the report is generated from the thread."/>
      <div style={{display:'grid', gridTemplateColumns:'repeat(4,1fr)', gap:14, marginBottom:24}}>
        <StatCard label="Projects in review" value={rows.length} sub="Submitted through Pamoja" accent={RV.blue} icon="list"/>
        <StatCard label="Responses due" value={due.length} sub="VVB has responded, your turn" accent={RV.gold} icon="reply"/>
        <StatCard label="Open findings" value={open.length} sub={`${reg.length - open.length} closed`} accent={RV.amber} icon="flag"/>
        <StatCard label="Median days in review" value="19" sub="Programme average 127" accent={RV.green} icon="clock"/>
      </div>
      <Card padding={0}>
        <div style={{padding:'18px 22px', borderBottom:'1px solid #F3F4F6'}}>
          <SectionHeader eyebrow="Active" title="Review queue" tail="Sorted by responses due" eyebrowColor={RV.blue}/>
        </div>
        <div style={{display:'grid', gridTemplateColumns:'1fr 150px 170px 110px 90px 90px', gap:14, padding:'10px 22px', fontSize:10, fontWeight:800, textTransform:'uppercase', letterSpacing:'0.08em', color:RV.faint, borderBottom:'1px solid #F3F4F6'}}>
          <span>Project</span><span>VVB</span><span>Review type</span><span>Open</span><span>Round</span><span>Days</span>
        </div>
        {rows.map(r => (
          <div key={r.id} onClick={() => r.active && onOpenProject()} style={{
            display:'grid', gridTemplateColumns:'1fr 150px 170px 110px 90px 90px', gap:14, padding:'16px 22px', alignItems:'center',
            borderBottom:'1px solid #F3F4F6', cursor: r.active ? 'pointer' : 'default', background: r.active ? '#fff' : '#FAFAFA',
          }}>
            <div>
              <div style={{fontSize:14, fontWeight:800, color:RV.ink}}>{r.name}</div>
              <div style={{fontSize:11, color:RV.muted, marginTop:2}}>{r.proponent} · <span style={{fontFamily:"'JetBrains Mono', monospace"}}>{r.id}</span> · {r.methodology}</div>
            </div>
            <div style={{fontSize:12, color: r.vvb.startsWith('Not') ? RV.faint : RV.ink}}>{r.vvb}</div>
            <div><Badge variant={r.review !== 'Pipeline listing' ? 'blue' : 'gray'}>{r.review}</Badge></div>
            <div style={{fontSize:13, fontWeight:800, color: r.due ? '#7C5104' : RV.ink}}>{r.open}{r.due ? <span style={{fontSize:11, fontWeight:700, color:'#7C5104'}}> · {r.due} due</span> : null}</div>
            <div style={{fontFamily:"'JetBrains Mono', monospace", fontSize:12, color:RV.muted}}>{r.round ? `R${r.round}` : '—'}</div>
            <div style={{fontFamily:"'JetBrains Mono', monospace", fontSize:12, color:RV.muted}}>{r.days}</div>
          </div>
        ))}
      </Card>
      <div style={{marginTop:18}}>
        <PreviewBanner tone="blue">Interactive concept. Pipeline listing and Project Hub data exchange follow Verra's Registration and Issuance Process v5.0; the review loop shown here is what Pamoja is building for EcoGreen.</PreviewBanner>
      </div>
    </main>
  );
}

/* --- Project documents by section: Project Description and Monitoring Report tabs ------------ */
const DOC_TABS = [
  { id:'PD', label:'Project Description', template:'VCS Project Description Template v4.4' },
  { id:'MR', label:'Monitoring Report',   template:'VCS Monitoring Report Template v4.4' },
];

function RegistryPD({ review, hero, dispatch, initialSection, onOpenFinding, seat = 'registry' }) {
  const isVvb = seat === 'vvb';
  const inScope = (f) => isVvb ? true : f.layer === 'registry_to_vvb';
  const init = initialSection && typeof initialSection === 'object' ? initialSection : (initialSection ? { doc:'PD', num:initialSection } : null);
  const [doc, setDoc] = React.useState(init ? init.doc : 'PD');
  const sections = sectionsForScope(review, doc);
  const flat = sections.flatMap(s => s.items);
  const [sel, setSel] = React.useState(init ? init.num : flat[0].num);
  const [raising, setRaising] = React.useState(false);
  React.useEffect(() => { if (init) { setDoc(init.doc); setSel(init.num); } }, [init && init.doc, init && init.num]);
  const switchDoc = (d) => { if (d === doc) return; setDoc(d); setSel(sectionsForScope(review, d).flatMap(s => s.items)[0].num); setRaising(false); };
  const item = flat.find(i => i.num === sel) || flat[0];
  const version = item.field_id ? latestVersion(review.versions, item.field_id) : null;
  const text = version ? (version.narrative || version.value) : item.narrative;
  const findingsHere = review.findings.filter(f => inScope(f) && f.scope_document === doc && f.anchor.section === item.num);
  const commentsHere = isVvb ? (review.comments || []).filter(c => c.doc === doc && c.section === item.num) : [];
  const fieldMeta = item.field_id ? (window.PHASE3_FIELDS || []).find(f => f.id === item.field_id) : null;
  const tab = DOC_TABS.find(t => t.id === doc);
  const openCount = (d) => review.findings.filter(f => inScope(f) && f.scope_document === d && f.status !== 'closed').length;
  return (
    <main style={{flex:1, padding:'28px 32px', background:RV.bg, minWidth:0}}>
      <ReviewPageHeader eyebrow={`${hero.name} · Project documents`} title={`${tab.label}, by section`}
        body={isVvb
          ? (doc === 'PD'
              ? 'The proponent\'s Project Description, section by section, from the current committed data. Raise a CAR, CL or FAR against any section, or leave a comment for the developer or a private note for your working papers.'
              : `Monitoring period 1, ${review.report.monitoring_period}. Raise verification findings here against the Monitoring Report; comments and notes work the same way as on the Project Description.`)
          : (doc === 'PD'
              ? 'Every section renders from the project\'s current committed data. Select a section to raise a finding against it; the finding anchors to that section and, where one exists, the underlying field.'
              : `Monitoring period 1, ${review.report.monitoring_period}. Sections render from the field-agent monitoring record. A finding raised here is scoped to the Monitoring Report and carries that suffix in its title, as Verra writes it.`)}
        right={<Badge variant="verra">VM0047 v1.1 · {review.report.review_type}</Badge>}/>
      <div style={{display:'grid', gridTemplateColumns:'280px 1fr', gap:18}}>
        <Card padding={0} style={{alignSelf:'start', position:'sticky', top:84}}>
          <div style={{display:'flex', borderBottom:'1px solid #F3F4F6'}}>
            {DOC_TABS.map(t => {
              const active = t.id === doc, n = openCount(t.id);
              return (
                <button key={t.id} type="button" onClick={()=>switchDoc(t.id)} title={t.template} style={{
                  flex:1, minHeight:44, border:'none', borderBottom: active ? `3px solid ${RV.gold}` : '3px solid transparent', background:'transparent', cursor:'pointer', fontFamily:'inherit',
                  fontSize:11, fontWeight:800, color: active ? RV.ink : RV.muted, display:'inline-flex', alignItems:'center', justifyContent:'center', gap:6, padding:'0 8px',
                }}>
                  <span style={{fontFamily:"'JetBrains Mono', monospace", fontSize:10, color: active ? RV.blue : RV.faint}}>{t.id}</span>
                  <span>{t.label}</span>
                  {n > 0 && <span style={{fontSize:9, fontWeight:800, color:'#92400E', background:'#FEF3C7', padding:'1px 6px', borderRadius:9999}}>{n}</span>}
                </button>
              );
            })}
          </div>
          <div style={{padding:'10px 16px 4px', fontSize:10, fontWeight:800, textTransform:'uppercase', letterSpacing:'0.1em', color:RV.faint}}>{tab.template}</div>
          <div style={{maxHeight:'calc(100vh - 260px)', overflowY:'auto'}}>
            {sections.map(s => (
              <div key={s.num}>
                <div style={{padding:'10px 16px 4px', fontSize:11, fontWeight:900, color:RV.ink}}><span style={{fontFamily:"'JetBrains Mono', monospace", color:RV.blue, marginRight:6}}>{s.num}</span>{s.title}</div>
                {s.items.map(it => {
                  const n = review.findings.filter(f => inScope(f) && f.scope_document === doc && f.anchor.section === it.num && f.status !== 'closed').length;
                  const active = it.num === sel;
                  return (
                    <button key={it.num} type="button" onClick={()=>{ setSel(it.num); setRaising(false); }} style={{
                      display:'flex', alignItems:'center', gap:8, width:'100%', textAlign:'left', padding:'8px 16px 8px 26px', minHeight:40,
                      background: active ? '#FFF8E0' : 'transparent', border:'none', borderRight: active ? `3px solid ${RV.gold}` : '3px solid transparent',
                      cursor:'pointer', fontFamily:'inherit', fontSize:12, color: active ? RV.ink : RV.muted, fontWeight: active ? 800 : 600,
                    }}>
                      <span style={{fontFamily:"'JetBrains Mono', monospace", fontSize:10, color:RV.blue, flexShrink:0}}>{it.num}</span>
                      <span style={{flex:1, minWidth:0, overflow:'hidden', textOverflow:'ellipsis', whiteSpace:'nowrap'}}>{it.title}</span>
                      {n > 0 && <span style={{fontSize:9, fontWeight:800, color:'#92400E', background:'#FEF3C7', padding:'1px 6px', borderRadius:9999}}>{n}</span>}
                    </button>
                  );
                })}
              </div>
            ))}
          </div>
        </Card>

        <div style={{display:'flex', flexDirection:'column', gap:14}}>
          <Card padding={0}>
            <div style={{padding:'18px 22px', borderBottom:'1px solid #F3F4F6', display:'flex', justifyContent:'space-between', alignItems:'flex-start', gap:14}}>
              <div>
                <div style={{fontSize:10, fontWeight:800, textTransform:'uppercase', letterSpacing:'0.12em', color:RV.blue}}>{tab.label} · Section {item.num}</div>
                <h2 style={{fontSize:20, fontWeight:900, color:RV.ink, margin:'2px 0 0'}}>{item.title}</h2>
                <div style={{display:'flex', gap:8, alignItems:'center', marginTop:8, flexWrap:'wrap'}}>
                  {version ? <>
                    <span style={{fontFamily:"'JetBrains Mono', monospace", fontSize:10, color:RV.blue, fontWeight:800, background:'#E8F4FC', padding:'2px 7px', borderRadius:4}}>{version.id}</span>
                    <span style={{fontSize:11, color:RV.muted}}>{version.author} · {fmtDate(version.date)}</span>
                    {version.hedera_anchor_id && <HederaChip id={version.hedera_anchor_id}/>}
                    {fieldMeta && <Badge variant="gray">{(FIELD_STATE[fieldMeta.state] || {}).lbl || fieldMeta.state}</Badge>}
                  </> : <span style={{fontSize:11, color:RV.faint}}>Narrative section · no single field · anchor by quoted text</span>}
                </div>
              </div>
              <Btn kind={raising ? 'secondary' : 'primary'} icon="flag" onClick={()=>setRaising(r=>!r)} style={{minHeight:40}}>{raising ? 'Cancel' : 'Raise finding'}</Btn>
            </div>
            <div style={{padding:'20px 22px'}}>
              <p style={{fontSize:14, lineHeight:1.75, color:RV.ink, margin:0}}>{text}</p>
              {version && version.value && version.narrative && (
                <div style={{marginTop:14, display:'inline-flex', alignItems:'center', gap:8, fontSize:12, color:RV.muted, background:RV.bg, border:`1px solid ${RV.line}`, borderRadius:8, padding:'6px 10px'}}>
                  <span style={{fontWeight:800, color:RV.ink}}>Field value</span> {version.value}
                </div>
              )}
            </div>
            {findingsHere.length > 0 && (
              <div style={{padding:'12px 22px 18px', borderTop:'1px solid #F3F4F6', display:'flex', gap:8, flexWrap:'wrap', alignItems:'center'}}>
                <span style={{fontSize:10, fontWeight:800, textTransform:'uppercase', letterSpacing:'0.1em', color:RV.faint, marginRight:4}}>Findings on this section</span>
                {findingsHere.map(f => (
                  <button key={f.id} type="button" onClick={()=>onOpenFinding(f.id)} style={{display:'inline-flex', alignItems:'center', gap:8, background:'#fff', border:`1px solid ${RV.line}`, borderRadius:8, padding:'6px 10px', cursor:'pointer', fontFamily:'inherit', fontSize:12, minHeight:36}}>
                    <span style={{fontFamily:"'JetBrains Mono', monospace", fontWeight:800}}>{f.id}</span> {f.title} <StatusChip status={f.status}/>{isVvb && f.layer === 'registry_to_vvb' && <Badge variant="verra">Verra</Badge>}
                  </button>
                ))}
              </div>
            )}
          </Card>

          {raising && <RaiseFindingDrawer item={item} doc={doc} review={review} seat={seat} onCancel={()=>setRaising(false)} onRaise={(p)=>{ dispatch(isVvb ? 'raiseVvbFinding' : 'raiseFinding', p); setRaising(false); }}/>}

          {isVvb && <SectionComments item={item} doc={doc} comments={commentsHere} onPost={(p)=>dispatch('addComment', { doc, section:item.num, field_id:item.field_id, ...p })}/>}

          {item.field_id && review.versions.filter(v => v.field_id === item.field_id).length > 1 && (
            <Card padding={0}>
              <div style={{padding:'14px 22px', borderBottom:'1px solid #F3F4F6'}}><SectionHeader eyebrow="Version history" title={`${review.versions.filter(v => v.field_id === item.field_id).length} versions of this section`} eyebrowColor={RV.blue}/></div>
              <div style={{padding:'6px 22px 14px'}}>
                {review.versions.filter(v => v.field_id === item.field_id).sort((a,b)=>b.version-a.version).map((v,i,arr) => (
                  <div key={v.id} style={{display:'grid', gridTemplateColumns:'90px 1fr 130px', gap:12, padding:'10px 0', borderBottom: i<arr.length-1 ? '1px dashed #F3F4F6' : 'none', alignItems:'center', fontSize:12}}>
                    <span style={{fontFamily:"'JetBrains Mono', monospace", fontWeight:800, color:RV.blue}}>v{v.version}</span>
                    <span style={{color:RV.ink}}>{v.value} <span style={{color:RV.faint}}>· {v.reason}</span></span>
                    <span style={{color:RV.muted, textAlign:'right'}}>{v.author.split(' ')[0]} · {fmtDate(v.date)}</span>
                  </div>
                ))}
              </div>
            </Card>
          )}
        </div>
      </div>
    </main>
  );
}

// Versions in force for a project validated before the 1 Jan 2027 change (verified 15 Oct 2026, see design brief section 14).
const RULE_VERSIONS = { 'VCS Standard':'v4.7', 'VCS Project Description Template':'v4.4', 'VCS Monitoring Report Template':'v4.4', 'VM0047':'v1.1' };

function RaiseFindingDrawer({ item, doc, review, onCancel, onRaise, seat = 'registry' }) {
  const scope = SCOPE_DOCS[doc] || SCOPE_DOCS.PD;
  const isVvb = seat === 'vvb';
  const [kind, setKind] = React.useState('CAR');
  const [due, setDue] = React.useState(VVB_KINDS.CAR.dueDays);
  const [note, setNote] = React.useState('');
  const pickKind = (k) => { setKind(k); setDue(VVB_KINDS[k].dueDays); };
  const [title, setTitle] = React.useState(item.title);
  const [quote, setQuote] = React.useState('');
  const [issues, setIssues] = React.useState(['']);
  const [std, setStd] = React.useState('VCS Standard');
  const [ver, setVer] = React.useState('v4.7');
  const [sec, setSec] = React.useState('');
  const ok = issues.some(t => t.trim());
  const S = { width:'100%', border:`1.5px solid ${RV.line}`, borderRadius:10, padding:'10px 12px', fontFamily:'inherit', fontSize:13, color:RV.ink, outline:'none', background:'#fff', minHeight:40 };
  const standards = ['VCS Standard', doc === 'MR' ? 'VCS Monitoring Report Template' : 'VCS Project Description Template', 'VM0047'];
  return (
    <Card style={{border:`1.5px solid ${RV.gold}`, background:'#FFFDF5'}} padding={20}>
      <div style={{display:'flex', justifyContent:'space-between', alignItems:'baseline', marginBottom:14}}>
        <div>
          <div style={{fontSize:10, fontWeight:800, textTransform:'uppercase', letterSpacing:'0.12em', color:RV.gold}}>{isVvb ? `New ${kind}` : 'New finding'}</div>
          <div style={{fontSize:16, fontWeight:900, color:RV.ink}}>Against {scope.label} Section {item.num} · {item.title}</div>
        </div>
        <span style={{fontSize:11, color:RV.muted}}>{isVvb ? 'Goes to the project developer as a change request. Closes when you verify their revision.' : 'Addressed to the VVB. The proponent is never addressed directly.'}</span>
      </div>
      {isVvb && (
        <div style={{display:'grid', gridTemplateColumns:'repeat(3,1fr)', gap:8, marginBottom:14}}>
          {Object.entries(VVB_KINDS).map(([k, m]) => (
            <button key={k} type="button" onClick={()=>pickKind(k)} style={{
              textAlign:'left', minHeight:44, borderRadius:10, cursor:'pointer', fontFamily:'inherit', padding:'10px 12px',
              background: kind===k ? '#fff' : 'transparent', border:`1.5px solid ${kind===k ? RV.gold : RV.line}`,
            }}>
              <div style={{display:'flex', alignItems:'center', gap:8}}>
                <span style={{fontFamily:"'JetBrains Mono', monospace", fontSize:11, fontWeight:800, color:RV.ink}}>{k}</span>
                <span style={{fontSize:12, fontWeight:800, color:RV.ink}}>{m.label}</span>
              </div>
              <div style={{fontSize:11, color:RV.muted, marginTop:4, lineHeight:1.45}}>{m.hint}</div>
            </button>
          ))}
        </div>
      )}
      <div style={{display:'grid', gridTemplateColumns:'1fr 1fr', gap:14}}>
        <label style={{fontSize:12}}><div style={{fontSize:10, fontWeight:800, textTransform:'uppercase', letterSpacing:'0.1em', color:RV.faint, marginBottom:6}}>Title</div>
          <div style={{display:'flex', alignItems:'center', gap:8}}>
            <input value={title} onChange={e=>setTitle(e.target.value)} style={S}/>
            <span title="Verra suffixes the title with the document in scope" style={{fontSize:12, color:RV.muted, whiteSpace:'nowrap'}}>– {scope.label}</span>
          </div>
        </label>
        <label style={{fontSize:12}}><div style={{fontSize:10, fontWeight:800, textTransform:'uppercase', letterSpacing:'0.1em', color:RV.faint, marginBottom:6}}>Quoted text (anchor)</div><input value={quote} onChange={e=>setQuote(e.target.value)} placeholder="Paste the words in the section this finding is about" style={S}/></label>
      </div>
      <div style={{marginTop:14}}>
        <div style={{fontSize:10, fontWeight:800, textTransform:'uppercase', letterSpacing:'0.1em', color:RV.faint, marginBottom:6}}>Issue</div>
        {issues.map((t,i) => (
          <div key={i} style={{display:'flex', gap:8, marginBottom:8, alignItems:'flex-start'}}>
            <span style={{fontFamily:"'JetBrains Mono', monospace", fontSize:11, fontWeight:800, color:RV.red, paddingTop:12}}>{i+1}.</span>
            <textarea value={t} onChange={e=>setIssues(a=>a.map((x,j)=>j===i?e.target.value:x))} placeholder="Cite the section, row and column, then state the inconsistency or omission." style={{...S, minHeight:64, resize:'vertical'}}/>
          </div>
        ))}
        <button type="button" onClick={()=>setIssues(a=>[...a,''])} style={{background:'transparent', border:'none', color:RV.goldText, fontWeight:800, fontSize:12, cursor:'pointer', fontFamily:'inherit', padding:0, minHeight:32}}>+ Add issue item</button>
        {issues.length > 1 && <span style={{fontSize:11, color:RV.muted, marginLeft:10}}>Each item can be closed or kept open separately in the registry response.</span>}
      </div>
      {isVvb ? (
        <div style={{marginTop:10, display:'grid', gridTemplateColumns:'1fr 120px', gap:10, alignItems:'end'}}>
          <label><div style={{fontSize:10, fontWeight:800, textTransform:'uppercase', letterSpacing:'0.1em', color:RV.faint, marginBottom:6}}>Action required of the developer</div>
            <textarea value={note} onChange={e=>setNote(e.target.value)} placeholder={`Tell the developer exactly what to change in Section ${item.num} and what evidence to attach.`} style={{...S, minHeight:64, resize:'vertical'}}/></label>
          <label><div style={{fontSize:10, fontWeight:800, textTransform:'uppercase', letterSpacing:'0.1em', color:RV.faint, marginBottom:6}}>Due in days</div>
            <input type="number" min="0" max="90" value={due == null ? '' : due} placeholder="none" onChange={e=>setDue(e.target.value === '' ? null : parseInt(e.target.value, 10))} style={S}/></label>
        </div>
      ) : (
      <div style={{marginTop:10}}>
        <div style={{fontSize:10, fontWeight:800, textTransform:'uppercase', letterSpacing:'0.1em', color:RV.faint, marginBottom:6}}>Action required</div>
        <div style={{fontSize:12, color:RV.muted, lineHeight:1.6, background:'#fff', border:`1px solid ${RV.line}`, borderRadius:10, padding:'10px 12px'}}>
          Verra's standard three actions are attached: the VVB must ensure the proponent updates Section {item.num} of the {scope.label}; the VVB must confirm the corrected information against evidence; the VVB must provide an independent assessment and update the {scope.report}.
        </div>
      </div>
      )}
      <div style={{marginTop:14, display:'grid', gridTemplateColumns:'1.4fr 0.8fr 0.8fr', gap:10}}>
        <label><div style={{fontSize:10, fontWeight:800, textTransform:'uppercase', letterSpacing:'0.1em', color:RV.faint, marginBottom:6}}>Program rule</div>
          <select value={std} onChange={e=>{ setStd(e.target.value); setVer(RULE_VERSIONS[e.target.value] || ''); }} style={S}>{standards.map(s => <option key={s}>{s}</option>)}</select></label>
        <label><div style={{fontSize:10, fontWeight:800, textTransform:'uppercase', letterSpacing:'0.1em', color:RV.faint, marginBottom:6}}>Version</div><input value={ver} onChange={e=>setVer(e.target.value)} style={S}/></label>
        <label><div style={{fontSize:10, fontWeight:800, textTransform:'uppercase', letterSpacing:'0.1em', color:RV.faint, marginBottom:6}}>Section</div><input value={sec} onChange={e=>setSec(e.target.value)} placeholder="3.11.2" style={S}/></label>
      </div>
      <div style={{display:'flex', justifyContent:'flex-end', gap:8, marginTop:16}}>
        <Btn kind="secondary" onClick={onCancel} style={{minHeight:40}}>Cancel</Btn>
        <Btn kind="primary" icon="flag" disabled={!ok || (isVvb && !note.trim())} style={{minHeight:40}} onClick={()=>onRaise({ kind, title, scope_document:doc, section:item.num, field_id:item.field_id, quote, issue:issues.filter(t=>t.trim()), actions:null, dueDays:due, note, rule: sec ? { standard:std, version:ver, section:sec } : null })}>{isVvb ? `Raise ${kind}, send to developer` : 'Raise finding, anchor to Hedera'}</Btn>
      </div>
    </Card>
  );
}

/* --- VVB comments on a section ------------------------------------------- */
function SectionComments({ item, doc, comments, onPost }) {
  const [audience, setAudience] = React.useState('developer');
  const [text, setText] = React.useState('');
  const post = () => { if (!text.trim()) return; onPost({ audience, text:text.trim() }); setText(''); };
  const S = { width:'100%', border:`1.5px solid ${RV.line}`, borderRadius:10, padding:'10px 12px', fontFamily:'inherit', fontSize:13, color:RV.ink, outline:'none', background:'#fff', minHeight:64, resize:'vertical' };
  return (
    <Card padding={0}>
      <div style={{padding:'14px 22px', borderBottom:'1px solid #F3F4F6', display:'flex', justifyContent:'space-between', alignItems:'baseline'}}>
        <SectionHeader eyebrow={`Comments · Section ${item.num}`} title={comments.length ? `${comments.length} comment${comments.length>1?'s':''} on this section` : 'No comments on this section yet'} eyebrowColor={RV.green}/>
        <span style={{fontSize:11, color:RV.muted}}>Comments to the developer appear on their change-requests page. Private notes stay in your working papers.</span>
      </div>
      {comments.length > 0 && (
        <div style={{padding:'8px 22px 4px', display:'flex', flexDirection:'column', gap:10}}>
          {comments.map(c => (
            <div key={c.id} style={{display:'flex', gap:12}}>
              <div style={{width:30, height:30, borderRadius:'50%', background:RV.green, color:RV.ink, display:'flex', alignItems:'center', justifyContent:'center', fontSize:10, fontWeight:900, flexShrink:0}}>SC</div>
              <div style={{flex:1, minWidth:0, background:RV.bg, border:`1px solid ${RV.line}`, borderRadius:10, padding:'10px 12px'}}>
                <div style={{display:'flex', justifyContent:'space-between', alignItems:'baseline', gap:8, marginBottom:4}}>
                  <span style={{fontSize:12, fontWeight:800, color:RV.ink}}>{c.author} <span style={{fontWeight:600, color:RV.muted}}>· {c.audience === 'private' ? 'Private note' : 'To the developer'}</span></span>
                  <span style={{fontSize:11, color:RV.faint, fontFamily:"'JetBrains Mono', monospace"}}>{c.id} · {fmtDate(c.date)}</span>
                </div>
                <div style={{fontSize:13, color:RV.ink, lineHeight:1.55}}>{c.text}</div>
              </div>
            </div>
          ))}
        </div>
      )}
      <div style={{padding:'12px 22px 18px'}}>
        <div style={{display:'flex', gap:6, marginBottom:8}}>
          {[['developer','To the developer'], ['private','Private note']].map(([k,l]) => (
            <button key={k} type="button" onClick={()=>setAudience(k)} style={{fontSize:11, fontWeight:800, padding:'6px 12px', borderRadius:8, minHeight:32, cursor:'pointer', fontFamily:'inherit', background: audience===k ? RV.ink : '#fff', color: audience===k ? '#fff' : RV.muted, border:`1px solid ${audience===k ? RV.ink : RV.line}`}}>{l}</button>
          ))}
        </div>
        <textarea value={text} onChange={e=>setText(e.target.value)} placeholder={audience === 'private' ? 'A note for your working papers. Not visible to the developer or the registry.' : `A comment for Grace on Section ${item.num}. Not a finding; use Raise finding for anything that must be corrected.`} style={S}/>
        <div style={{display:'flex', justifyContent:'flex-end', marginTop:8}}>
          <Btn kind="primary" icon="reply" disabled={!text.trim()} onClick={post} style={{minHeight:40}}>{audience === 'private' ? 'Save note' : 'Post comment'}</Btn>
        </div>
      </div>
    </Card>
  );
}

/* --- Findings list + thread ---------------------------------------------- */
function RegistryFindings({ review, hero, dispatch, selectedId, onSelect, onOpenSection }) {
  const reg = review.findings.filter(f => f.layer === 'registry_to_vvb');
  const [filter, setFilter] = React.useState('all');
  const list = reg.filter(f => filter === 'all' ? true : filter === 'open' ? f.status !== 'closed' : f.status === 'closed');
  const sel = reg.find(f => f.id === selectedId) || list[0] || reg[0];
  return (
    <main style={{flex:1, padding:'28px 32px', background:RV.bg, minWidth:0}}>
      <ReviewPageHeader eyebrow={`${hero.name} · ${review.report.review_type} review`} title="Findings"
        body="Each finding is anchored to a section of the Project Description, the Monitoring Report or the VVB's report, and cites a program rule. The VVB responds; you close or keep open each item with a specific further ask."
        right={<div style={{display:'flex', gap:4}}>{['all','open','closed'].map(k => <button key={k} type="button" onClick={()=>setFilter(k)} style={{fontSize:11, fontWeight:800, padding:'6px 12px', borderRadius:8, minHeight:32, cursor:'pointer', fontFamily:'inherit', background: filter===k ? RV.ink : '#fff', color: filter===k ? '#fff' : RV.muted, border:`1px solid ${filter===k ? RV.ink : RV.line}`, textTransform:'capitalize'}}>{k}</button>)}</div>}/>
      <div style={{display:'grid', gridTemplateColumns:'320px 1fr', gap:18}}>
        <div style={{display:'flex', flexDirection:'column', gap:8}}>
          {list.length === 0 && <EmptyState icon="check" title="Nothing here" body="No findings match this filter."/>}
          {list.map(f => <FindingListRow key={f.id} finding={f} seat="registry" active={sel && sel.id === f.id} onClick={()=>onSelect(f.id)}/>)}
        </div>
        <div style={{minWidth:0}}>{sel ? <ReviewThread finding={sel} seat="registry" review={review} dispatch={dispatch} onOpenSection={()=>onOpenSection(sel.anchor.section, sel.scope_document)}/> : <EmptyState icon="flag" title="No finding selected"/>}</div>
      </div>
    </main>
  );
}

/* --- Project Review Report: template v4.2 layout ------------------------------
 * The same ReportDocument renders the on-screen preview and the PDF. Layout
 * follows Verra's Project Review Report template v4.2: header table, then a
 * FINDINGS table with #, Finding Description (Issue, Action Required,
 * Program Rule(s)), VVB Response (per round, VVB then Verra response) and
 * Status. A4 landscape, v4.2 in the footer with the page number.
 * ------------------------------------------------------------------------- */
const DOC = {
  font:"'Satoshi','Manrope',ui-sans-serif,system-ui,-apple-system,sans-serif",
  mono:"'JetBrains Mono', monospace",
  ink:'#111827', muted:'#4B5563', line:'#B9C0C8', head:'#E9EDF1', width:1000,
};
function ReportDocument({ review }) {
  const rep = review.report;
  const reg = review.findings.filter(f => f.layer === 'registry_to_vvb').sort((a,b)=>a.number-b.number);
  const td = { border:`1px solid ${DOC.line}`, padding:'7px 10px', verticalAlign:'top', fontSize:11, lineHeight:1.5, color:DOC.ink };
  const th = { ...td, background:DOC.head, fontWeight:800, textAlign:'left', fontSize:10, letterSpacing:'0.04em' };
  const h = { fontSize:11, fontWeight:800, color:DOC.ink, margin:'7px 0 2px' };
  const ol = { margin:'0 0 0 2px', paddingLeft:16 };
  const mono = { fontFamily:DOC.mono, fontSize:10.5 };
  const HeaderRow = ({ k, v }) => (
    <tr><td style={{...td, width:200, fontWeight:800, background:DOC.head}}>{k}</td><td style={td}>{v}</td></tr>
  );
  const Items = ({ items, numbered }) => numbered
    ? <ol style={ol}>{items.map(it => <li key={it.n} style={{marginBottom:3}}>{it.text}</li>)}</ol>
    : <div>{items[0] ? items[0].text : ''}</div>;
  const rounds = (f) => f.rounds.filter(r => r.vvb_response || r.registry_response || f.status !== 'closed' || r.n === 1);
  return (
    <div className="pj-report-doc" style={{width:DOC.width, background:'#fff', color:DOC.ink, fontFamily:DOC.font, padding:'26px 32px 30px', boxSizing:'border-box'}}>
      <div style={{display:'flex', justifyContent:'space-between', alignItems:'center', borderBottom:`2px solid ${DOC.ink}`, paddingBottom:8}}>
        <div style={{display:'flex', alignItems:'center', gap:10}}>
          <img src="brand/logo-mark.svg" alt="Pamoja" style={{height:26}}/>
          <span style={{fontSize:11, fontWeight:800, color:DOC.muted}}>Pamoja dMRV · review record</span>
        </div>
        <div style={{fontSize:10, fontWeight:800, letterSpacing:'0.14em', textTransform:'uppercase', color:DOC.muted}}>Project Review Report</div>
      </div>
      <h1 style={{textAlign:'center', fontSize:20, fontWeight:900, letterSpacing:'0.06em', margin:'18px 0 10px', color:DOC.ink}}>PROJECT REVIEW REPORT</h1>
      <p style={{fontSize:11, lineHeight:1.55, margin:'0 0 14px', color:DOC.ink}}>
        This project review report holds the findings raised during the registry's review of the project specified below. The VVB must address each finding before the project request can be considered for approval. The report is generated from the Pamoja review record, not retyped: header fields come from the project record, and each finding carries its issue, action required, program rules and every round of VVB and registry response. Demo prototype; every value on this page is synthetic.
      </p>
      <table style={{width:'100%', borderCollapse:'collapse', tableLayout:'fixed'}} className="pj-avoid">
        <tbody>
          <HeaderRow k="Project ID" v={<span style={mono}>{rep.project_id} · Verra ID {rep.registry_project_id}</span>}/>
          <HeaderRow k="Project Name" v={rep.project_name}/>
          <HeaderRow k="Review Type" v={rep.review_type}/>
          <HeaderRow k="Program(s)" v={rep.programs.join(', ')}/>
          <HeaderRow k="Project Proponent" v={rep.proponent}/>
          <HeaderRow k="VVB" v={rep.vvb}/>
          <HeaderRow k="Assessment Criteria" v={rep.assessment_criteria}/>
          <HeaderRow k="Date of First Issue" v={fmtDate(rep.date_first_issue)}/>
          <HeaderRow k="Date of Second Issue" v={fmtDate(rep.date_second_issue)}/>
          <HeaderRow k="Review Conclusion" v={rep.conclusion || 'Pending'}/>
          <HeaderRow k="Date of Final Issue" v={fmtDate(rep.date_final_issue)}/>
        </tbody>
      </table>

      <div style={{fontSize:12, fontWeight:900, letterSpacing:'0.1em', margin:'20px 0 8px', color:DOC.ink}}>FINDINGS</div>
      <table style={{width:'100%', borderCollapse:'collapse', tableLayout:'fixed'}}>
        <colgroup><col style={{width:30}}/><col style={{width:'46%'}}/><col/><col style={{width:66}}/></colgroup>
        <thead>
          <tr><th style={th}>#</th><th style={th}>Finding Description</th><th style={th}>VVB Response</th><th style={{...th, textAlign:'center'}}>Status</th></tr>
        </thead>
        <tbody>
          {reg.map(f => (
            <tr key={f.id} className="pj-avoid">
              <td style={{...td, textAlign:'center', fontWeight:800}}>{f.number}.</td>
              <td style={td}>
                <div style={{fontWeight:800, fontSize:11.5, marginBottom:4}}>{findingTitle(f)}</div>
                <div style={h}>Issue</div>
                <div style={{fontSize:10.5, color:DOC.muted, marginBottom:2}}>Section {f.anchor.section} of the {(SCOPE_DOCS[f.scope_document] || SCOPE_DOCS.PD).label}{f.anchor.row != null ? `, row ${f.anchor.row}` : ''}{f.anchor.column != null ? `, column ${f.anchor.column}` : ''}</div>
                <Items items={f.issue} numbered={f.issue.length > 1}/>
                <div style={h}>Action Required</div>
                <ol style={ol}>{f.actions_required.map(a => <li key={a.n} style={{marginBottom:3}}>{a.text}</li>)}</ol>
                <div style={h}>Program Rule(s)</div>
                <div>{f.program_rules.map((r,i) => <span key={i}>{i>0 ? '; ' : ''}{r.standard}, {r.version}, Section <span style={mono}>{r.section}</span></span>)}{f.program_rules.length === 0 && '—'}</div>
                <div style={{...mono, fontSize:9, color:DOC.muted, marginTop:8}}>Hedera testnet 0.0.8321350 · {f.hedera_anchor_ids.length} anchor{f.hedera_anchor_ids.length>1?'s':''} · last {f.hedera_anchor_ids[f.hedera_anchor_ids.length-1]}</div>
              </td>
              <td style={td}>
                {rounds(f).map(r => {
                  const rr = r.registry_response, items = rr && responseItems(rr);
                  return (
                    <div key={r.n} style={{marginBottom:10}}>
                      <div style={{...h, margin:'0 0 2px'}}>Round {r.n}</div>
                      <div style={{fontWeight:800}}>VVB Response{!r.vvb_response && <span style={{fontWeight:600, color:DOC.muted}}> (Pending)</span>}</div>
                      {r.vvb_response && <div style={{marginBottom:6}}>{r.vvb_response.text}</div>}
                      <div style={{fontWeight:800}}>Verra Response{!rr && <span style={{fontWeight:600, color:DOC.muted}}> (Pending)</span>}</div>
                      {rr && (items
                        ? <ol style={ol}>{items.map(it => <li key={it.n} style={{marginBottom:3}}>{it.text}</li>)}</ol>
                        : <div>{rr.text}</div>)}
                    </div>
                  );
                })}
              </td>
              <td style={{...td, textAlign:'center', fontWeight:800}}>{f.status === 'closed' ? 'Closed' : 'Open'}</td>
            </tr>
          ))}
        </tbody>
      </table>
      <div style={{display:'flex', justifyContent:'space-between', marginTop:14, fontSize:9.5, color:DOC.muted}}>
        <span>Issues: {rep.issues.map(i => `${i.n} (${fmtDate(i.date)})`).join(' · ')}{rep.monitoring_period ? ` · Monitoring period 1: ${rep.monitoring_period}` : ''}</span>
        <span style={mono}>Hedera testnet · 0.0.8321350</span>
      </div>
    </div>
  );
}

/* Download the document as a PDF file (A4 landscape, v4.2 and page number in the footer). Falls back to the print dialog if html2pdf did not load. */
function exportReportPdf(review, el) {
  const rep = review.report;
  const name = `Project-Review-Report_${rep.project_id}_${reviewToday()}.pdf`;
  if (!window.html2pdf || !el) { window.print(); return Promise.resolve('print'); }
  const opt = {
    margin:[10, 9, 13, 9], filename:name,
    image:{ type:'jpeg', quality:0.96 },
    html2canvas:{ scale:2, useCORS:true, backgroundColor:'#ffffff', logging:false, windowWidth:DOC.width + 64 },
    jsPDF:{ unit:'mm', format:'a4', orientation:'landscape' },
    pagebreak:{ mode:['css','legacy'], avoid:['.pj-avoid'] },
  };
  return window.html2pdf().set(opt).from(el).toPdf().get('pdf').then(pdf => {
    const n = pdf.internal.getNumberOfPages();
    const w = pdf.internal.pageSize.getWidth(), hgt = pdf.internal.pageSize.getHeight();
    for (let i = 1; i <= n; i++) {
      pdf.setPage(i); pdf.setFontSize(8); pdf.setTextColor(100);
      pdf.text('v4.2', 9, hgt - 6);
      pdf.text(`${rep.project_name} · ${rep.project_id} · Project Review Report · Pamoja dMRV demo prototype, synthetic data`, w / 2, hgt - 6, { align:'center' });
      pdf.text(String(i), w - 9, hgt - 6, { align:'right' });
    }
    pdf.save(name);
    return name;
  });
}

function RegistryReport({ review, hero, dispatch }) {
  const rep = review.report;
  const reg = review.findings.filter(f => f.layer === 'registry_to_vvb');
  const open = reg.filter(f => f.status !== 'closed').length;
  const docRef = React.useRef(null);
  const [busy, setBusy] = React.useState(false);
  const [done, setDone] = React.useState(null);
  const download = () => {
    setBusy(true); setDone(null);
    exportReportPdf(review, docRef.current).then(name => { setDone(name); }).catch(() => { window.print(); }).finally(() => setBusy(false));
  };
  return (
    <main style={{flex:1, padding:'28px 32px', background:RV.bg, minWidth:0}}>
      <style>{`
        @page { size: A4 landscape; margin: 10mm 9mm 13mm 9mm; }
        @media print {
          .pj-side, header, footer, .no-print, .pj-report-chrome { display:none !important; }
          main { padding:0 !important; background:#fff !important; }
          .pj-report-frame { border:none !important; box-shadow:none !important; padding:0 !important; background:#fff !important; overflow:visible !important; }
          .pj-report-doc { width:auto !important; padding:0 !important; }
          .pj-avoid { page-break-inside: avoid; break-inside: avoid; }
        }
      `}</style>
      <div className="pj-report-chrome">
        <ReviewPageHeader eyebrow={`${hero.name} · ${rep.review_type} review`} title="Project Review Report"
          body="Rendered in Verra's Project Review Report template v4.2 layout from the finding thread, not retyped. Download PDF writes the same document to an A4 landscape PDF file; the final report can be issued once every finding is closed."
          right={<div className="no-print" style={{display:'flex', gap:8}}>
            <Btn kind="secondary" icon="download" onClick={download} disabled={busy} style={{minHeight:40}}>{busy ? 'Preparing PDF…' : 'Download PDF'}</Btn>
            <Btn kind="primary" icon="signature" disabled={open > 0 || !!rep.date_final_issue} onClick={()=>dispatch('issueReport', { kind:'final' })} style={{minHeight:40}} title={open > 0 ? `${open} finding(s) still open` : ''}>{rep.date_final_issue ? 'Final issued' : 'Issue final report'}</Btn>
          </div>}/>
        {open > 0 && <div className="no-print" style={{marginBottom:14}}><PreviewBanner tone="gold">{open} finding{open>1?'s':''} still open. The final report can be issued once every finding is closed.</PreviewBanner></div>}
        {done && <div className="no-print" style={{marginBottom:14}}><PreviewBanner tone="blue">Saved <span style={{fontFamily:"'JetBrains Mono', monospace"}}>{done}</span>. A4 landscape, v4.2 footer with page numbers.</PreviewBanner></div>}
        <div className="no-print" style={{display:'flex', justifyContent:'space-between', alignItems:'center', marginBottom:10, fontSize:11, color:RV.muted}}>
          <span><b style={{color:RV.ink}}>Preview</b> · {rep.template} · A4 landscape · {reg.length} finding{reg.length>1?'s':''}, {open} open</span>
          <span style={{fontFamily:"'JetBrains Mono', monospace"}}>Hedera testnet · 0.0.8321350</span>
        </div>
      </div>
      <div className="pj-report-frame" style={{background:'#E5E7EB', border:`1px solid ${RV.line}`, borderRadius:10, padding:'22px', overflowX:'auto'}}>
        <div style={{width:DOC.width, margin:'0 auto', boxShadow:'0 2px 14px rgba(2,44,40,0.14)'}}>
          <div ref={docRef}><ReportDocument review={review}/></div>
        </div>
      </div>
    </main>
  );
}

window.RegistryQueue = RegistryQueue;
window.RegistryPD = RegistryPD;
window.RegistryFindings = RegistryFindings;
window.RegistryReport = RegistryReport;
window.ReportDocument = ReportDocument;
window.exportReportPdf = exportReportPdf;
