/* ================================================================
 * VVB seat — Registry findings inbox + workspace.
 *
 * The VVB sits between the registry and the developer. For each
 * registry finding they open a change request, review the developer's
 * new version against the redline, cite numbered evidence, and send the
 * VVB response. Layer-1 findings (CAR / CL / FAR) use the same thread
 * with the VVB as the party that raised them.
 * ================================================================ */

function VvbRegistryFindings({ review, dispatch, hero, selectedId, onSelect, onOpenSection }) {
  const layerOf = (id) => { const f = review.findings.find(x => x.id === id); return f && f.layer === 'vvb_to_developer' ? 'validation' : 'registry'; };
  const [tab, setTab] = React.useState(() => layerOf(selectedId));
  React.useEffect(() => { if (selectedId) setTab(layerOf(selectedId)); }, [selectedId]);
  const list = review.findings.filter(f => tab === 'registry' ? f.layer === 'registry_to_vvb' : f.layer === 'vvb_to_developer');
  const sel = list.find(f => f.id === selectedId) || list.find(f => f.status === 'pending_vvb') || list[0];
  const todo = review.findings.filter(f => f.layer === 'registry_to_vvb' && f.status === 'pending_vvb').length;
  return (
    <main style={{flex:1, padding:'28px 32px', background:RV.bg, minWidth:0}}>
      <ReviewPageHeader eyebrow={`${hero.name} · ${review.report.review_type}`} title="Findings"
        body="Verra addresses you, never the proponent. Findings against the Project Description or Monitoring Report go to the developer as a change request; findings against your own validation or verification report you answer directly. Check the redline when a field comes back, cite the evidence you validated, and respond."
        right={<div style={{display:'flex', gap:4}}>
          {[['registry','Registry findings', review.findings.filter(f=>f.layer==='registry_to_vvb').length], ['validation','Your CAR / CL / FAR', review.findings.filter(f=>f.layer==='vvb_to_developer').length]].map(([k,l,n]) => (
            <button key={k} type="button" onClick={()=>setTab(k)} style={{fontSize:11, fontWeight:800, padding:'6px 12px', borderRadius:8, minHeight:32, cursor:'pointer', fontFamily:'inherit', background: tab===k ? RV.ink : '#fff', color: tab===k ? '#fff' : RV.muted, border:`1px solid ${tab===k ? RV.ink : RV.line}`}}>{l} <span style={{opacity:0.6}}>{n}</span></button>
          ))}
        </div>}/>
      <div style={{display:'grid', gridTemplateColumns:'repeat(4,1fr)', gap:14, marginBottom:20}}>
        <StatCard label="Your turn" value={todo} sub="Registry findings waiting on you" accent={RV.gold} icon="reply"/>
        <StatCard label="With the developer" value={review.findings.filter(f=>f.status==='pending_developer').length} sub="Change requests open" accent={RV.amber} icon="clock"/>
        <StatCard label="With the registry" value={review.findings.filter(f=>f.status==='pending_registry').length} sub="Responses sent, awaiting Verra" accent={RV.blue} icon="shield"/>
        <StatCard label="Closed" value={review.findings.filter(f=>f.status==='closed').length} sub="All layers" accent={RV.green} icon="check"/>
      </div>
      <div style={{display:'grid', gridTemplateColumns:'320px 1fr', gap:18}}>
        <div style={{display:'flex', flexDirection:'column', gap:8}}>
          {list.map(f => <FindingListRow key={f.id} finding={f} seat="vvb" active={sel && sel.id === f.id} onClick={()=>onSelect(f.id)}/>)}
        </div>
        <div style={{minWidth:0}}>
          {sel ? <VvbWorkspace finding={sel} review={review} dispatch={dispatch} onOpenSection={onOpenSection}/> : <EmptyState icon="flag" title="Nothing to review"/>}
        </div>
      </div>
    </main>
  );
}

/* Field column: current value, version history, redline against what the registry last saw. */
function VvbWorkspace({ finding, review, dispatch, onOpenSection }) {
  const fieldId = finding.anchor.field_id;
  const versions = fieldId ? review.versions.filter(v => v.field_id === fieldId).sort((a,b)=>a.version-b.version) : [];
  const current = versions[versions.length-1] || null;
  const base = baselineVersionFor(review, finding);
  const sec = sectionOfFinding(review, finding);
  const scope = SCOPE_DOCS[finding.scope_document] || SCOPE_DOCS.PD;
  return (
    <div style={{display:'flex', flexDirection:'column', gap:14}}>
      {fieldId && current && (
        <Card padding={0}>
          <div style={{padding:'14px 20px', borderBottom:'1px solid #F3F4F6', display:'flex', justifyContent:'space-between', alignItems:'center', gap:12}}>
            <SectionHeader eyebrow={`Anchored field · ${scope.label} §${finding.anchor.section}`} title={sec ? sec.title : finding.anchor.section_title} eyebrowColor={RV.blue}
              tail={<span>Current <span style={{fontFamily:"'JetBrains Mono', monospace", color:RV.blue, fontWeight:800}}>{current.id}</span> · {versions.length} version{versions.length>1?'s':''}</span>}/>
          </div>
          <div style={{padding:'14px 20px'}}>
            {base && base.id !== current.id ? (
              <Redline before={base.narrative || base.value} after={current.narrative || current.value}
                labelBefore={`${base.id} · what the registry last saw`} labelAfter={`${current.id} · ${current.author.split(' ')[0]}, ${fmtDate(current.date)}`}/>
            ) : (
              <div style={{fontSize:13, lineHeight:1.7, color:RV.ink, padding:'10px 12px', background:RV.bg, border:`1px solid ${RV.line}`, borderRadius:10}}>
                {current.narrative || current.value}
                <div style={{fontSize:11, color:RV.faint, marginTop:6}}>No change since the registry last saw this section.</div>
              </div>
            )}
            <div style={{display:'flex', gap:8, marginTop:10, flexWrap:'wrap', alignItems:'center'}}>
              {versions.map(v => <span key={v.id} title={`${v.author} · ${fmtDate(v.date)} · ${v.reason}`} style={{fontFamily:"'JetBrains Mono', monospace", fontSize:10, fontWeight:800, color: v.id === current.id ? '#fff' : RV.blue, background: v.id === current.id ? RV.blue : '#E8F4FC', padding:'2px 7px', borderRadius:4}}>v{v.version}</span>)}
              {current.hedera_anchor_id && <HederaChip id={current.hedera_anchor_id}/>}
            </div>
          </div>
        </Card>
      )}
      <ReviewThread finding={finding} seat="vvb" review={review} dispatch={dispatch} onOpenSection={onOpenSection ? () => onOpenSection({ doc: finding.scope_document, num: finding.anchor.section }) : undefined}/>
    </div>
  );
}

window.VvbRegistryFindings = VvbRegistryFindings;
