/* ================================================================
 * Registry Review — shared thread components.
 *
 * One ReviewThread, three seats. The seat decides which parts render
 * and which composer is live:
 *   registry  : sees issue, actions, rules, VVB responses, its own
 *               responses. Never sees the change request.
 *   vvb       : sees everything. Opens change requests, writes the
 *               VVB response.
 *   developer : does not use ReviewThread (see dev-change-requests.jsx).
 * ================================================================ */

const RV = {
  ink:'#022C28', gold:'#F4C300', goldText:'#B8960A', muted:'#6B7280', faint:'#9CA3AF',
  line:'#E5E7EB', bg:'#F9FAFB', blue:'#0077B6', green:'#2BC48A', amber:'#D97706', red:'#DC2626',
};
const mono = { fontFamily:"'JetBrains Mono', monospace" };
const eyebrow = { fontSize:10, fontWeight:800, textTransform:'uppercase', letterSpacing:'0.12em', color:RV.faint };

/* --- Demo prototype chip (every Registry Review screen) -------- */
function DemoChip({ style }) {
  return (
    <span title="Interactive concept built with Verra's review loop in mind. Production VVB workspace at pamojadmrv.earth." style={{
      display:'inline-flex', alignItems:'center', gap:6, fontSize:10, fontWeight:800, letterSpacing:'0.08em', textTransform:'uppercase',
      color:'#7C5104', background:'#FFF8E0', border:'1px solid #FDE68A', padding:'4px 9px', borderRadius:9999, whiteSpace:'nowrap', ...style,
    }}>
      <span style={{width:6, height:6, borderRadius:'50%', background:RV.gold}}/>
      Demo prototype
    </span>
  );
}

/* --- Page header used by every review screen ------------------- */
function ReviewPageHeader({ eyebrow: eb, title, body, right }) {
  return (
    <div style={{display:'flex', justifyContent:'space-between', alignItems:'flex-start', gap:24, marginBottom:22, flexWrap:'wrap'}}>
      <div style={{minWidth:0}}>
        <div style={{fontSize:11, fontWeight:800, letterSpacing:'0.12em', textTransform:'uppercase', color:RV.gold, marginBottom:4}}>{eb}</div>
        <h1 style={{fontSize:28, fontWeight:900, color:RV.ink, letterSpacing:'-0.02em', margin:0, lineHeight:1.1}}>{title}</h1>
        {body && <p style={{fontSize:14, color:RV.muted, margin:'6px 0 0', maxWidth:760, lineHeight:1.55}}>{body}</p>}
      </div>
      <div style={{display:'flex', alignItems:'center', gap:10, flexShrink:0}}>
        {right}
        <DemoChip/>
      </div>
    </div>
  );
}

/* --- Small chips ------------------------------------------------ */
function StatusChip({ status, developerView = false }) {
  let meta = STATUS_META[status] || STATUS_META.raised;
  if (developerView) {
    meta = { pending_developer:{ label:'Requested', tone:'amber' }, pending_vvb:{ label:'Handed back', tone:'blue' }, pending_registry:{ label:'Handed back', tone:'blue' }, closed:{ label:'Accepted', tone:'green' }, raised:{ label:'Requested', tone:'amber' } }[status] || meta;
  }
  return <Badge variant={meta.tone} dot>{meta.label}</Badge>;
}
function AnchorChip({ anchor, scope = 'PD', onClick }) {
  const d = SCOPE_DOCS[scope] || SCOPE_DOCS.PD;
  const loc = [anchor.row != null && `row ${anchor.row}`, anchor.column != null && `col ${anchor.column}`].filter(Boolean).join(', ');
  return (
    <button onClick={onClick} type="button" title={onClick ? `Open Section ${anchor.section} of the ${d.label}` : `Section ${anchor.section} of the VVB's ${d.label}`} style={{
      display:'inline-flex', alignItems:'center', gap:6, background:'#fff', border:`1px solid ${RV.line}`, borderRadius:8,
      padding:'4px 9px', cursor: onClick ? 'pointer' : 'default', fontFamily:'inherit', fontSize:11, color:RV.ink, fontWeight:700,
    }}>
      <span style={{...mono, color:RV.blue, fontWeight:800}}>{scope !== 'PD' ? `${d.short} ` : ''}§{anchor.section}</span>
      <span>{anchor.section_title}</span>
      {loc && <span style={{color:RV.faint, fontWeight:600}}>· {loc}</span>}
    </button>
  );
}
function EvidenceChip({ id, evidence }) {
  const doc = (evidence || window.EVIDENCE_DOCS).find(d => d.id === id);
  return (
    <span title={doc ? `${doc.filename} · sha256 ${doc.sha256}` : ''} style={{
      display:'inline-flex', alignItems:'center', gap:6, background:'#F3F4F6', border:`1px solid ${RV.line}`, borderRadius:8,
      padding:'3px 8px', fontSize:11, color:RV.ink, fontWeight:600,
    }}>
      <PamojaIcon name="document" size={11} color={RV.muted} stroke={1.8}/>
      <span style={{...mono, fontWeight:800}}>{id}</span>_{doc ? doc.title : 'Document'}
    </span>
  );
}
function HederaChip({ id }) {
  return (
    <span title="Anchored to Hedera Consensus Service (testnet)" style={{display:'inline-flex', alignItems:'center', gap:6, ...mono, fontSize:10, color:'#7C5CFC', background:'rgba(124,92,252,0.08)', padding:'3px 8px', borderRadius:6}}>
      <PamojaIcon name="hedera" size={11} color="#7C5CFC" stroke={1.8}/>{id}<span style={{color:RV.faint}}>testnet</span>
    </span>
  );
}
function RuleChip({ rule }) {
  return (
    <span title={rule.verify ? 'Citation to be verified against the methodology registry before showing to Verra' : ''} style={{display:'inline-flex', alignItems:'center', gap:6, fontSize:11, color:RV.ink, background:'#fff', border:`1px solid ${RV.line}`, borderRadius:8, padding:'3px 8px', fontWeight:600}}>
      <span style={{fontWeight:800}}>{rule.standard}</span> {rule.version} <span style={{...mono, color:RV.blue}}>§{rule.section}</span>
      {rule.verify && <span style={{fontSize:9, fontWeight:800, color:'#7C5104', background:'#FFF8E0', padding:'1px 5px', borderRadius:4, letterSpacing:'0.06em'}}>VERIFY</span>}
    </span>
  );
}

/* --- Round strip: one step per party per round ------------------ */
function RoundStrip({ finding, seat }) {
  const steps = [];
  const devDoc = isDeveloperDocument(finding.scope_document);
  steps.push({ k:'raised', label:'Raised', date:finding.raised_by.date, done:true });
  finding.rounds.forEach(r => {
    if (seat !== 'registry' && devDoc) {
      steps.push({ k:`cr${r.n}`, label:`R${r.n} change request`, date:r.change_request && r.change_request.date, done:!!r.change_request });
      steps.push({ k:`hb${r.n}`, label:`R${r.n} handed back`, date:r.change_request && r.change_request.developer_handback && r.change_request.developer_handback.date, done:!!(r.change_request && r.change_request.developer_handback) });
    }
    steps.push({ k:`vr${r.n}`, label:`R${r.n} VVB response`, date:r.vvb_response && r.vvb_response.date, done:!!r.vvb_response });
    if (finding.layer === 'registry_to_vvb') steps.push({ k:`rr${r.n}`, label:`R${r.n} registry response`, date:r.registry_response && r.registry_response.date, done:!!r.registry_response, outcome:r.registry_response && r.registry_response.outcome, label2: r.registry_response && responseItems(r.registry_response) ? roundOutcomeLabel(r.registry_response) : null });
  });
  const currentIdx = steps.findIndex(s => !s.done);
  return (
    <div style={{display:'flex', alignItems:'stretch', gap:0, overflowX:'auto', padding:'2px 0', minWidth:0, maxWidth:'100%'}}>
      {steps.map((s, i) => {
        const isCurrent = i === currentIdx;
        const color = s.done ? (s.outcome === 'open' ? RV.amber : RV.green) : isCurrent ? RV.gold : RV.line;
        return (
          <div key={s.k} style={{display:'flex', alignItems:'center', flexShrink:0}}>
            <div style={{display:'flex', flexDirection:'column', alignItems:'center', minWidth:96}}>
              <span style={{width:10, height:10, borderRadius:'50%', background: s.done || isCurrent ? color : '#fff', border:`2px solid ${color}`, boxShadow: isCurrent ? `0 0 0 4px ${hexToRgba(RV.gold,0.25)}` : 'none'}}/>
              <span style={{fontSize:10, fontWeight:800, color: s.done ? RV.ink : isCurrent ? '#7C5104' : RV.faint, marginTop:6, textAlign:'center', lineHeight:1.2}}>{s.label}</span>
              <span style={{fontSize:10, color:RV.faint, ...mono, marginTop:2}}>{s.done ? fmtDate(s.date) : isCurrent ? 'now' : '—'}</span>
              {s.label2 && <span style={{fontSize:9, fontWeight:800, color:'#7C5104', marginTop:2}}>{s.label2}</span>}
            </div>
            {i < steps.length-1 && <div style={{width:26, height:2, background: s.done ? RV.green : RV.line, marginBottom:30}}/>}
          </div>
        );
      })}
    </div>
  );
}

/* --- Redline ---------------------------------------------------- */
function Redline({ before, after, labelBefore = 'Previous version', labelAfter = 'Current version', defaultMode = 'inline' }) {
  const [mode, setMode] = React.useState(defaultMode);
  const ops = React.useMemo(() => wordDiff(before, after), [before, after]);
  const changed = ops.filter(o => o.type !== 'same').length;
  const seg = { marginBottom:0, padding:'2px 3px', borderRadius:4 };
  return (
    <div style={{border:`1px solid ${RV.line}`, borderRadius:10, overflow:'hidden', background:'#fff'}}>
      <div style={{display:'flex', justifyContent:'space-between', alignItems:'center', padding:'10px 14px', borderBottom:`1px solid #F3F4F6`, background:RV.bg}}>
        <div style={{display:'flex', alignItems:'center', gap:10}}>
          <span style={eyebrow}>Tracked changes</span>
          <span style={{fontSize:11, color:RV.muted}}>{changed === 0 ? 'No changes' : `${changed} change${changed>1?'s':''} between versions`}</span>
        </div>
        <div style={{display:'flex', gap:4}}>
          {['inline','side'].map(m => (
            <button key={m} type="button" onClick={()=>setMode(m)} style={{
              fontSize:11, fontWeight:800, padding:'4px 10px', borderRadius:6, cursor:'pointer', fontFamily:'inherit', minHeight:28,
              background: mode===m ? RV.ink : 'transparent', color: mode===m ? '#fff' : RV.muted, border:`1px solid ${mode===m ? RV.ink : RV.line}`,
            }}>{m === 'inline' ? 'Inline' : 'Side by side'}</button>
          ))}
        </div>
      </div>
      {mode === 'inline' ? (
        <div style={{padding:'14px 16px', fontSize:13, lineHeight:1.7, color:RV.ink}}>
          {ops.map((o, i) => o.type === 'same' ? <span key={i}>{o.text}</span>
            : o.type === 'del' ? <span key={i} style={{...seg, background:'#FEE2E2', color:'#991B1B', textDecoration:'line-through'}}>{o.text}</span>
            : <span key={i} style={{...seg, background:'#D1FAE5', color:'#065F46', fontWeight:700}}>{o.text}</span>)}
        </div>
      ) : (
        <div style={{display:'grid', gridTemplateColumns:'1fr 1fr'}}>
          <div style={{padding:'12px 16px', borderRight:`1px solid #F3F4F6`}}>
            <div style={{...eyebrow, marginBottom:6}}>{labelBefore}</div>
            <div style={{fontSize:13, lineHeight:1.7, color:RV.ink}}>{ops.filter(o=>o.type!=='ins').map((o,i)=> o.type==='del' ? <span key={i} style={{...seg, background:'#FEE2E2', color:'#991B1B'}}>{o.text}</span> : <span key={i}>{o.text}</span>)}</div>
          </div>
          <div style={{padding:'12px 16px'}}>
            <div style={{...eyebrow, marginBottom:6}}>{labelAfter}</div>
            <div style={{fontSize:13, lineHeight:1.7, color:RV.ink}}>{ops.filter(o=>o.type!=='del').map((o,i)=> o.type==='ins' ? <span key={i} style={{...seg, background:'#D1FAE5', color:'#065F46', fontWeight:700}}>{o.text}</span> : <span key={i}>{o.text}</span>)}</div>
          </div>
        </div>
      )}
    </div>
  );
}

/* --- Finding header + static parts ------------------------------ */
function FindingHeader({ finding, seat, onOpenSection }) {
  const sev = finding.severity && { major:{bg:'#FEE2E2', fg:'#991B1B'}, minor:{bg:'#FEF3C7', fg:'#92400E'}, observation:{bg:'#E8F4FC', fg:'#0C4A6E'} }[finding.severity];
  return (
    <div style={{padding:'20px 24px', borderBottom:`1px solid #F3F4F6`}}>
      <div style={{display:'flex', alignItems:'center', gap:10, marginBottom:8, flexWrap:'wrap'}}>
        <span style={{...mono, fontSize:11, fontWeight:800, color:RV.ink, background:'#F3F4F6', padding:'3px 8px', borderRadius:6}}>{finding.id}</span>
        {sev && <span style={{fontSize:10, fontWeight:800, letterSpacing:'0.06em', color:sev.fg, background:sev.bg, padding:'3px 8px', borderRadius:6}}>{finding.severity.toUpperCase()}</span>}
        <StatusChip status={finding.status}/>
        <span style={{fontSize:11, color:RV.muted}}>{finding.review_type} · {(SCOPE_DOCS[finding.scope_document] || SCOPE_DOCS.PD).label}</span>
      </div>
      <h2 style={{fontSize:20, fontWeight:900, color:RV.ink, margin:'0 0 10px', letterSpacing:'-0.01em'}}>{finding.number}. {findingTitle(finding)}</h2>
      <div style={{display:'flex', alignItems:'center', gap:8, flexWrap:'wrap'}}>
        <AnchorChip anchor={finding.anchor} scope={finding.scope_document} onClick={isDeveloperDocument(finding.scope_document) ? onOpenSection : undefined}/>
        {finding.program_rules.map((r,i) => <RuleChip key={i} rule={r}/>)}
      </div>
      <div style={{fontSize:12, color:RV.muted, marginTop:10}}>
        Raised {fmtDate(finding.raised_by.date)} by <b style={{color:RV.ink}}>{finding.raised_by.name}</b>, {finding.raised_by.org}
      </div>
    </div>
  );
}
function ItemOutcomeChip({ state, round }) {
  const closed = state === 'closed';
  return (
    <span title={closed ? (round ? `Closed by the registry in round ${round}` : 'Closed') : 'Still open'} style={{display:'inline-flex', alignItems:'center', gap:5, fontSize:9, fontWeight:800, letterSpacing:'0.06em', textTransform:'uppercase', whiteSpace:'nowrap',
      color: closed ? '#065F46' : '#7C5104', background: closed ? '#D1FAE5' : '#FEF3C7', padding:'2px 7px', borderRadius:9999, marginLeft:8, verticalAlign:'middle'}}>
      <span style={{width:5, height:5, borderRadius:'50%', background: closed ? RV.green : RV.amber}}/>{closed ? (round ? `Closed R${round}` : 'Closed') : 'Open'}
    </span>
  );
}
/* states: optional map n -> { state, round } rendered as a chip per item (per-item outcomes, Verra 3197 finding 7). */
function NumberedBlock({ title, items, tone, states }) {
  return (
    <div>
      <div style={{...eyebrow, marginBottom:8}}>{title}</div>
      <ol style={{margin:0, paddingLeft:0, listStyle:'none', display:'flex', flexDirection:'column', gap:8}}>
        {items.map(it => (
          <li key={it.n} style={{display:'flex', gap:10, fontSize:13, lineHeight:1.55, color:RV.ink}}>
            <span style={{...mono, fontSize:11, fontWeight:800, color: tone || RV.blue, paddingTop:2, flexShrink:0}}>{it.n}.</span>
            <span>{it.text}{it.owner === 'vvb' && <span style={{fontSize:10, fontWeight:800, color:RV.faint, marginLeft:6, letterSpacing:'0.06em'}}>VVB</span>}{states && states[it.n] && <ItemOutcomeChip state={states[it.n].state} round={states[it.n].round}/>}</span>
          </li>
        ))}
      </ol>
    </div>
  );
}
/* The registry's numbered per-item response, each ending "The issue is open" or "The issue is closed". */
function ResponseItems({ items }) {
  return (
    <ol style={{margin:'2px 0 0', paddingLeft:0, listStyle:'none', display:'flex', flexDirection:'column', gap:8}}>
      {items.map(it => (
        <li key={it.n} style={{display:'flex', gap:10, fontSize:13, lineHeight:1.6, color:RV.ink}}>
          <span style={{...mono, fontSize:11, fontWeight:800, color:RV.blue, paddingTop:2, flexShrink:0}}>{it.n}.</span>
          <span>{it.text}<ItemOutcomeChip state={it.outcome} round={null}/></span>
        </li>
      ))}
    </ol>
  );
}

/* --- One round ----------------------------------------------------- */
function ResponseCard({ who, initials, accent, date, title, text, children, pending }) {
  return (
    <div style={{display:'flex', gap:12, opacity: pending ? 0.6 : 1}}>
      <div style={{width:32, height:32, borderRadius:'50%', background:accent, color:RV.ink, display:'flex', alignItems:'center', justifyContent:'center', fontSize:11, fontWeight:900, flexShrink:0}}>{initials}</div>
      <div style={{flex:1, minWidth:0, background:'#fff', border:`1px solid ${RV.line}`, borderRadius:10, padding:'12px 14px'}}>
        <div style={{display:'flex', justifyContent:'space-between', alignItems:'baseline', gap:10, marginBottom:6}}>
          <span style={{fontSize:12, fontWeight:800, color:RV.ink}}>{title} <span style={{fontWeight:600, color:RV.muted}}>· {who}</span></span>
          <span style={{fontSize:11, color:RV.faint, ...mono}}>{date ? fmtDate(date) : 'pending'}</span>
        </div>
        {text && <div style={{fontSize:13, color:RV.ink, lineHeight:1.6}}>{text}</div>}
        {children}
      </div>
    </div>
  );
}
function RoundCard({ round, finding, seat, review }) {
  const cr = round.change_request, hb = cr && cr.developer_handback;
  const prior = React.useMemo(() => {
    // the version before this round's handback
    if (!hb) return null;
    const v = versionById(review.versions, hb.field_version_id);
    if (!v) return null;
    return review.versions.filter(x => x.field_id === v.field_id && x.version < v.version).sort((a,b)=>b.version-a.version)[0] || null;
  }, [hb, review.versions]);
  const hbVersion = hb ? versionById(review.versions, hb.field_version_id) : null;
  const empty = !cr && !round.vvb_response && !round.registry_response;
  return (
    <div style={{borderLeft:`3px solid ${round.registry_response ? (round.registry_response.outcome === 'closed' ? RV.green : RV.amber) : RV.gold}`, paddingLeft:16, marginBottom:4}}>
      <div style={{display:'flex', alignItems:'center', gap:10, marginBottom:12}}>
        <span style={{fontSize:12, fontWeight:900, color:RV.ink, letterSpacing:'0.02em'}}>Round {round.n}</span>
        {round.registry_response && <Badge variant={round.registry_response.outcome === 'closed' ? 'green' : 'amber'} dot>{roundOutcomeLabel(round.registry_response)}</Badge>}
        {empty && <span style={{fontSize:11, color:RV.faint}}>{round.n > 1 ? 'Opened by the registry response above. Waiting on the VVB.' : 'Waiting on the VVB.'}</span>}
      </div>
      <div style={{display:'flex', flexDirection:'column', gap:12}}>
        {seat !== 'registry' && cr && (
          <ResponseCard who="Sarah Chen, VVB" initials="SC" accent={RV.green} date={cr.date} title={`Change request ${cr.id}`} text={cr.note}>
            <div style={{fontSize:11, color:RV.muted, marginTop:6}}>{cr.due_days ? `Due in ${cr.due_days} days` : 'No due date (forward action)'} · to Grace Kimani, project developer</div>
          </ResponseCard>
        )}
        {seat !== 'registry' && hb && (
          <ResponseCard who="Grace Kimani, developer" initials="GK" accent={RV.gold} date={hb.date} title="Handed back" text={hb.note}>
            <div style={{display:'flex', gap:6, flexWrap:'wrap', marginTop:8, alignItems:'center'}}>
              <span style={{...mono, fontSize:10, color:RV.blue, fontWeight:800, background:'#E8F4FC', padding:'2px 7px', borderRadius:4}}>{hb.field_version_id}</span>
              {hb.evidence_doc_ids.map(id => <EvidenceChip key={id} id={id} evidence={review.evidence}/>)}
              {hbVersion && hbVersion.hedera_anchor_id && <HederaChip id={hbVersion.hedera_anchor_id}/>}
            </div>
            {prior && hbVersion && (
              <div style={{marginTop:12}}>
                <Redline before={prior.narrative || prior.value} after={hbVersion.narrative || hbVersion.value} labelBefore={`v${prior.version} · ${fmtDate(prior.date)}`} labelAfter={`v${hbVersion.version} · ${fmtDate(hbVersion.date)}`}/>
              </div>
            )}
          </ResponseCard>
        )}
        {round.vvb_response ? (
          <ResponseCard who="Sarah Chen, SCS Global Services" initials="SC" accent={RV.green} date={round.vvb_response.date} title="VVB response" text={round.vvb_response.text}>
            <div style={{display:'flex', gap:6, flexWrap:'wrap', marginTop:8, alignItems:'center'}}>
              {round.vvb_response.evidence_doc_ids.map(id => <EvidenceChip key={id} id={id} evidence={review.evidence}/>)}
              {round.vvb_response.field_version_ids.map(id => <span key={id} style={{...mono, fontSize:10, color:RV.blue, fontWeight:800, background:'#E8F4FC', padding:'2px 7px', borderRadius:4}}>{id}</span>)}
              {round.vvb_response.report_section_updated && <Badge variant="gray">{round.vvb_response.report_section_updated}</Badge>}
            </div>
          </ResponseCard>
        ) : (cr || seat === 'registry') && !empty ? (
          <ResponseCard who="SCS Global Services" initials="SC" accent={RV.green} title="VVB response" pending/>
        ) : null}
        {finding.layer === 'registry_to_vvb' && (round.registry_response ? (
          <ResponseCard who="Priya Nair, Verra" initials="PN" accent="#BAE0F7" date={round.registry_response.date} title="Registry response" text={round.registry_response.text}>
            {responseItems(round.registry_response) && <ResponseItems items={responseItems(round.registry_response)}/>}
            {round.registry_response.outcome === 'open' && round.registry_response.follow_up_ask && (
              <div style={{marginTop:8, padding:'8px 10px', background:'#FEF3C7', border:'1px solid #FDE68A', borderRadius:8, fontSize:12, color:'#7C5104'}}><b>Further ask.</b> {round.registry_response.follow_up_ask}</div>
            )}
          </ResponseCard>
        ) : round.vvb_response ? (
          <ResponseCard who="Verra" initials="PN" accent="#BAE0F7" title="Registry response" pending/>
        ) : null)}
      </div>
    </div>
  );
}

/* --- Composers -------------------------------------------------------- */
const ta = { width:'100%', minHeight:84, border:`1.5px solid ${RV.line}`, borderRadius:10, padding:'10px 12px', fontFamily:'inherit', fontSize:13, resize:'vertical', color:RV.ink, outline:'none', background:'#fff' };
const inp = { ...ta, minHeight:40, resize:'none' };
function ComposerShell({ title, hint, children }) {
  return (
    <div style={{marginTop:18, border:`1.5px solid ${RV.gold}`, borderRadius:10, padding:16, background:'#FFFDF5'}}>
      <div style={{display:'flex', justifyContent:'space-between', alignItems:'baseline', marginBottom:10}}>
        <span style={{fontSize:12, fontWeight:900, color:RV.ink}}>{title}</span>
        {hint && <span style={{fontSize:11, color:RV.muted}}>{hint}</span>}
      </div>
      {children}
    </div>
  );
}
function ChangeRequestComposer({ finding, onSend }) {
  const r = currentRound(finding);
  const prevAsk = finding.rounds.length > 1 ? finding.rounds[finding.rounds.length-2].registry_response : null;
  const [note, setNote] = React.useState(prevAsk && prevAsk.follow_up_ask ? prevAsk.follow_up_ask : '');
  const [due, setDue] = React.useState(10);
  return (
    <ComposerShell title={`Open change request to the developer · round ${r.n}`} hint="The developer sees this note and the anchored field. They never see the registry's text.">
      <textarea value={note} onChange={e=>setNote(e.target.value)} placeholder="Tell the developer exactly which field to change and what evidence to attach." style={ta}/>
      <div style={{display:'flex', justifyContent:'space-between', alignItems:'center', marginTop:10, gap:10}}>
        <label style={{fontSize:12, color:RV.muted, display:'inline-flex', alignItems:'center', gap:8}}>Due in
          <input type="number" min="1" max="60" value={due} onChange={e=>setDue(parseInt(e.target.value||'0',10))} style={{...inp, width:70, minHeight:36, padding:'6px 8px'}}/> days
        </label>
        <Btn kind="primary" icon="arrowRight" disabled={!note.trim()} onClick={()=>onSend({ note, dueDays:due })} style={{minHeight:40}}>Send change request</Btn>
      </div>
    </ComposerShell>
  );
}
function VvbResponseComposer({ finding, review, onSend }) {
  const r = currentRound(finding);
  const hb = r.change_request && r.change_request.developer_handback;
  const v = hb ? versionById(review.versions, hb.field_version_id) : null;
  const sec = finding.anchor.section;
  const scope = SCOPE_DOCS[finding.scope_document] || SCOPE_DOCS.PD;
  const ownReport = !isDeveloperDocument(finding.scope_document);
  const reportLabel = scope.report.charAt(0).toUpperCase() + scope.report.slice(1);
  const defaultText = v ? `${scope.label} Section ${sec} updated in version ${v.version}. VVB ${finding.scope_document === 'MR' ? 'verified' : 'validated'} the change against ${hb.evidence_doc_ids.map(id => { const d = review.evidence.find(x=>x.id===id); return d ? `document ${d.id}_${d.title}` : `document ${id}`; }).join(', ')} by desk review. `
    : ownReport ? `Section ${sec} of the ${scope.report} corrected in the revision submitted with this response. ` : '';
  const [text, setText] = React.useState(defaultText);
  const [docs, setDocs] = React.useState(hb ? hb.evidence_doc_ids : []);
  const [section, setSection] = React.useState(ownReport ? `${reportLabel} §${sec}` : `${reportLabel} §${finding.scope_document === 'MR' ? '3.1' : '3.2'}`);
  const toggle = (id) => setDocs(d => d.includes(id) ? d.filter(x=>x!==id) : [...d, id]);
  return (
    <ComposerShell title={`VVB response · round ${r.n}`} hint={ownReport ? `This finding is against your own ${scope.report}. Correct the report and respond; no change request to the developer is needed.` : 'Name the section, the value, and how you validated it. Vague words reopen findings.'}>
      <textarea value={text} onChange={e=>setText(e.target.value)} style={ta}/>
      <div style={{marginTop:10}}>
        <div style={{...eyebrow, marginBottom:6}}>Evidence cited</div>
        <div style={{display:'flex', gap:6, flexWrap:'wrap'}}>
          {review.evidence.map(d => (
            <button key={d.id} type="button" onClick={()=>toggle(d.id)} style={{background:'transparent', border:'none', padding:0, cursor:'pointer', opacity: docs.includes(d.id) ? 1 : 0.45, fontFamily:'inherit'}}>
              <EvidenceChip id={d.id} evidence={review.evidence}/>
            </button>
          ))}
        </div>
      </div>
      <div style={{display:'flex', justifyContent:'space-between', alignItems:'flex-end', marginTop:12, gap:12}}>
        <label style={{fontSize:12, color:RV.muted, flex:1}}>
          <div style={{...eyebrow, marginBottom:6}}>{reportLabel} section updated</div>
          <input value={section} onChange={e=>setSection(e.target.value)} style={inp}/>
        </label>
        <Btn kind="primary" icon="arrowRight" disabled={!text.trim()} onClick={()=>onSend({ text, evidenceDocIds:docs, reportSection:section })} style={{minHeight:40}}>Send to registry</Btn>
      </div>
    </ComposerShell>
  );
}
/* Verra ends every response item with "The issue is open" or "The issue is closed". Append it when the reviewer did not. */
function withOutcomeSentence(outcome, text) {
  const s = text.trim().replace(/\s+$/, '');
  if (/the (issue|finding) is (open|closed)\.?$/i.test(s)) return s.endsWith('.') ? s : s + '.';
  return `${s}${/[.!?]$/.test(s) ? '' : '.'} The issue is ${outcome === 'closed' ? 'closed' : 'open'}.`;
}
function OutcomeToggle({ value, onChange, compact }) {
  return (
    <div style={{display:'flex', gap:6}}>
      {[['closed','The issue is closed', RV.green], ['open','The issue is open', RV.amber]].map(([k, l, c]) => (
        <button key={k} type="button" onClick={()=>onChange(k)} style={{
          flex: compact ? 'none' : 1, minHeight: compact ? 32 : 44, padding: compact ? '0 10px' : 0, borderRadius: compact ? 8 : 10, cursor:'pointer', fontFamily:'inherit', fontSize: compact ? 11 : 13, fontWeight:800,
          background: value===k ? hexToRgba(c, 0.12) : '#fff', color: value===k ? RV.ink : RV.muted, border:`1.5px solid ${value===k ? c : RV.line}`,
        }}>{compact ? (k === 'closed' ? 'Closed' : 'Open') : l}</button>
      ))}
    </div>
  );
}
function RegistryResponseComposer({ finding, onSend }) {
  const r = currentRound(finding);
  const perItem = finding.issue.length > 1;
  const openItems = openIssueItems(finding);
  const closedEarlier = finding.issue.filter(it => itemOutcome(finding, it.n).state === 'closed');
  const [outcome, setOutcome] = React.useState('closed');
  const [text, setText] = React.useState('');
  const [ask, setAsk] = React.useState('');
  const [items, setItems] = React.useState(() => openItems.map(it => ({ n:it.n, outcome:'closed', text:'' })));
  const setItem = (n, patch) => setItems(a => a.map(x => x.n === n ? { ...x, ...patch } : x));
  const anyOpen = perItem ? items.some(i => i.outcome === 'open') : outcome === 'open';
  const openCount = perItem ? items.filter(i => i.outcome === 'open').length : (outcome === 'open' ? 1 : 0);
  const canSend = perItem ? items.length > 0 && items.every(i => i.text.trim()) && (!anyOpen || ask.trim()) : text.trim() && (!anyOpen || ask.trim());
  const send = () => perItem
    ? onSend({ items: items.map(i => ({ n:i.n, outcome:i.outcome, text: withOutcomeSentence(i.outcome, i.text) })), outcome: anyOpen ? 'open' : 'closed', followUpAsk:ask })
    : onSend({ text: withOutcomeSentence(outcome, text), outcome, followUpAsk:ask });
  return (
    <ComposerShell title={`Registry response · round ${r.n}`} hint={perItem ? 'Respond to each open item. An item can close while another stays open; the finding stays open until every item is closed.' : 'Close only when the revised document names the section, the value, and how the VVB validated it.'}>
      {perItem ? (
        <div style={{display:'flex', flexDirection:'column', gap:10}}>
          {closedEarlier.length > 0 && (
            <div style={{fontSize:11, color:RV.muted, background:'#fff', border:`1px solid ${RV.line}`, borderRadius:8, padding:'8px 10px'}}>
              {closedEarlier.map(it => <span key={it.n} style={{marginRight:10}}>Item <b style={{...mono}}>{it.n}</b> closed in round {itemOutcome(finding, it.n).round}.</span>)} Only the open items are answered below.
            </div>
          )}
          {items.map(it => {
            const issue = finding.issue.find(x => x.n === it.n);
            return (
              <div key={it.n} style={{background:'#fff', border:`1px solid ${RV.line}`, borderRadius:10, padding:'10px 12px'}}>
                <div style={{display:'flex', justifyContent:'space-between', alignItems:'flex-start', gap:12, marginBottom:8}}>
                  <div style={{display:'flex', gap:8, fontSize:12, color:RV.muted, lineHeight:1.5, minWidth:0}}>
                    <span style={{...mono, fontSize:11, fontWeight:800, color:RV.red, flexShrink:0}}>{it.n}.</span>
                    <span style={{overflow:'hidden', textOverflow:'ellipsis', display:'-webkit-box', WebkitLineClamp:2, WebkitBoxOrient:'vertical'}}>{issue ? issue.text : ''}</span>
                  </div>
                  <OutcomeToggle compact value={it.outcome} onChange={(v)=>setItem(it.n, { outcome:v })}/>
                </div>
                <textarea value={it.text} onChange={e=>setItem(it.n, { text:e.target.value })} placeholder={it.outcome === 'closed' ? 'State what now satisfies this item.' : 'State precisely what still does not satisfy this item.'} style={{...ta, minHeight:64}}/>
              </div>
            );
          })}
        </div>
      ) : (
        <>
          <div style={{marginBottom:10}}><OutcomeToggle value={outcome} onChange={setOutcome}/></div>
          <textarea value={text} onChange={e=>setText(e.target.value)} placeholder={outcome === 'closed' ? 'State what now satisfies the finding.' : 'State precisely what still does not satisfy the finding.'} style={ta}/>
        </>
      )}
      {anyOpen && (
        <input value={ask} onChange={e=>setAsk(e.target.value)} placeholder="Further ask: the specific change required in the next round." style={{...inp, marginTop:8}}/>
      )}
      <div style={{display:'flex', justifyContent:'space-between', alignItems:'center', marginTop:10, gap:10}}>
        <span style={{fontSize:11, color:RV.muted}}>Each item will end with "The issue is closed" or "The issue is open", as Verra writes it.</span>
        <Btn kind="primary" icon="arrowRight" disabled={!canSend} onClick={send} style={{minHeight:40}}>{!anyOpen ? 'Close finding' : perItem && items.length > 1 ? `Keep ${openCount} item${openCount > 1 ? 's' : ''} open, start next round` : 'Keep open, start next round'}</Btn>
      </div>
    </ComposerShell>
  );
}

/* --- The thread ----------------------------------------------------- */
function ReviewThread({ finding, seat, review, dispatch, onOpenSection }) {
  const r = currentRound(finding);
  const devDoc   = isDeveloperDocument(finding.scope_document);
  const needsCR  = seat === 'vvb' && finding.status === 'pending_vvb' && devDoc && !r.change_request;
  const needsVR  = seat === 'vvb' && finding.status === 'pending_vvb' && !r.vvb_response && (!devDoc || (r.change_request && r.change_request.developer_handback));
  const issueStates = finding.layer === 'registry_to_vvb' && finding.issue.length > 1 ? Object.fromEntries(finding.issue.map(it => [it.n, itemOutcome(finding, it.n)])) : null;
  const waitDev  = seat === 'vvb' && finding.status === 'pending_developer';
  const needsRR  = seat === 'registry' && finding.status === 'pending_registry';
  const waitVvb  = seat === 'registry' && (finding.status === 'pending_vvb' || finding.status === 'pending_developer');
  return (
    <div style={{background:'#fff', border:`1px solid ${RV.line}`, borderRadius:10, overflow:'hidden'}}>
      <FindingHeader finding={finding} seat={seat} onOpenSection={onOpenSection}/>
      <div style={{padding:'16px 24px', borderBottom:`1px solid #F3F4F6`, background:RV.bg}}>
        <RoundStrip finding={finding} seat={seat}/>
      </div>
      <div style={{padding:'20px 24px', display:'grid', gridTemplateColumns:'1fr 1fr', gap:24, borderBottom:`1px solid #F3F4F6`}}>
        <NumberedBlock title="Issue" items={finding.issue} tone={RV.red} states={issueStates}/>
        <NumberedBlock title="Action required" items={finding.actions_required}/>
      </div>
      <div style={{padding:'20px 24px', display:'flex', flexDirection:'column', gap:22}}>
        {finding.rounds.map(rd => <RoundCard key={rd.n} round={rd} finding={finding} seat={seat} review={review}/>)}
        {needsCR && <ChangeRequestComposer finding={finding} onSend={(p)=>dispatch('openChangeRequest', { findingId:finding.id, ...p })}/>}
        {needsVR && <VvbResponseComposer finding={finding} review={review} onSend={(p)=>dispatch('sendVvbResponse', { findingId:finding.id, ...p })}/>}
        {needsRR && <RegistryResponseComposer finding={finding} onSend={(p)=>dispatch('sendRegistryResponse', { findingId:finding.id, ...p })}/>}
        {waitDev && <PreviewBanner tone="gold">Change request {r.change_request.id} is with the developer. You will be able to respond once they hand the field back.</PreviewBanner>}
        {waitVvb && <PreviewBanner tone="blue">Waiting on the VVB. The project proponent is never addressed directly by the registry.</PreviewBanner>}
        {finding.status === 'closed' && <PreviewBanner tone="gray">Closed. Every round above is immutable and anchored: {finding.hedera_anchor_ids.slice(-1).map(id => <HederaChip key={id} id={id}/>)}</PreviewBanner>}
      </div>
    </div>
  );
}

/* --- Findings list (shared by registry and VVB seats) ----------------- */
function FindingListRow({ finding, active, onClick, seat }) {
  const r = currentRound(finding);
  const next = seat === 'registry'
    ? ({ pending_registry:'Your response is due', pending_vvb:'With the VVB', pending_developer:'With the VVB', closed:'Closed' })[finding.status]
    : ({ pending_vvb: (r.change_request && r.change_request.developer_handback) || !isDeveloperDocument(finding.scope_document) ? 'Write your response' : 'Open a change request', pending_developer:'With the developer', pending_registry:'With the registry', closed:'Closed' })[finding.status];
  return (
    <button type="button" onClick={onClick} style={{
      width:'100%', textAlign:'left', background: active ? '#FFF8E0' : '#fff', border: active ? `1.5px solid ${RV.gold}` : `1px solid ${RV.line}`,
      borderRadius:10, padding:'12px 14px', cursor:'pointer', fontFamily:'inherit', minHeight:44,
    }}>
      <div style={{display:'flex', alignItems:'center', gap:8, marginBottom:5}}>
        <span style={{...mono, fontSize:10, fontWeight:800, color:RV.ink}}>{finding.id}</span>
        <StatusChip status={finding.status}/>
        <span style={{marginLeft:'auto', fontSize:10, color:RV.faint, ...mono}}>R{r.n}</span>
      </div>
      <div style={{fontSize:13, fontWeight:800, color:RV.ink, lineHeight:1.35, marginBottom:4}}>{finding.number}. {findingTitle(finding)}</div>
      <div style={{fontSize:11, color:RV.muted, display:'flex', justifyContent:'space-between', gap:8}}>
        <span style={{...mono, color:RV.blue}}>{finding.scope_document !== 'PD' ? `${(SCOPE_DOCS[finding.scope_document] || {}).short || ''} ` : ''}§{finding.anchor.section}</span>
        <span style={{fontWeight:700, color: finding.status === 'closed' ? '#059669' : '#7C5104'}}>{next}</span>
      </div>
    </button>
  );
}

window.RV = RV; window.DemoChip = DemoChip; window.ReviewPageHeader = ReviewPageHeader;
window.StatusChip = StatusChip; window.AnchorChip = AnchorChip; window.EvidenceChip = EvidenceChip; window.HederaChip = HederaChip; window.RuleChip = RuleChip;
window.RoundStrip = RoundStrip; window.Redline = Redline; window.ReviewThread = ReviewThread; window.FindingListRow = FindingListRow;
window.NumberedBlock = NumberedBlock; window.ResponseCard = ResponseCard; window.ResponseItems = ResponseItems; window.ItemOutcomeChip = ItemOutcomeChip;
