/* ================================================================
 * Project developer seat — Change requests.
 *
 * The developer sees change requests from the VVB, each pointing at one
 * field or section. They edit the field (a new version), attach numbered
 * evidence, and hand back. They never see registry text, the registry
 * reviewer's name, or registry responses. Status is shown only as
 * Requested / Handed back / Accepted / Needs another change.
 * ================================================================ */

function ChangeRequestsView({ review, dispatch, hero, onOpenProject }) {
  // Every finding whose current round has a change request is a CR for the developer.
  const crs = review.findings
    .filter(f => f.rounds.some(r => r.change_request))
    .map(f => {
      const rounds = f.rounds.filter(r => r.change_request);
      const r = rounds[rounds.length-1];
      const needsAnother = f.rounds.length > 1 && f.status === 'pending_developer';
      return { finding:f, round:r, cr:r.change_request, needsAnother };
    })
    .sort((a,b) => (a.finding.status === 'pending_developer' ? 0 : 1) - (b.finding.status === 'pending_developer' ? 0 : 1));
  const [selId, setSelId] = React.useState(crs.length ? crs[0].finding.id : null);
  const sel = crs.find(c => c.finding.id === selId) || crs[0];
  const openCount = crs.filter(c => c.finding.status === 'pending_developer').length;
  return (
    <main style={{flex:1, padding:'28px 32px', background:RV.bg, minWidth:0}}>
      <ReviewPageHeader eyebrow="Trust · Your actions" title="Change requests"
        body="Requests from your VVB, each pointing at one field of your Project Description or Monitoring Report. Edit the field, attach evidence, and hand it back. Sampling, adjudication and sign-off remain VVB actions."/>
      <VvbCommentsForDeveloper comments={(review.comments || []).filter(c => c.audience === 'developer')}/>
      <div style={{display:'grid', gridTemplateColumns:'320px 1fr', gap:18}}>
        <div>
          <div style={{display:'flex', gap:8, marginBottom:10}}>
            <span style={{fontSize:11, fontWeight:800, color:RV.faint, letterSpacing:'0.1em', textTransform:'uppercase'}}>Open ({openCount})</span>
          </div>
          <div style={{display:'flex', flexDirection:'column', gap:8}}>
            {crs.map(c => <CrListItem key={c.finding.id} c={c} active={sel && sel.finding.id === c.finding.id} onClick={()=>setSelId(c.finding.id)}/>)}
          </div>
          <div style={{marginTop:14, padding:14, background:'#fff', border:`1px solid ${RV.line}`, borderRadius:10}}>
            <div style={{...{fontSize:11, fontWeight:800, color:RV.faint, letterSpacing:'0.1em', textTransform:'uppercase'}, marginBottom:6}}>Other projects</div>
            <div style={{fontSize:12, color:RV.ink, lineHeight:1.5}}>No open change requests on your other projects.</div>
          </div>
        </div>
        <div style={{minWidth:0}}>
          {sel ? <ChangeRequestDetail c={sel} review={review} dispatch={dispatch} project={hero} onOpenProject={onOpenProject}/> : <EmptyState icon="check" title="No change requests" body="Your VVB has not asked for any changes."/>}
        </div>
      </div>
    </main>
  );
}

function CrListItem({ c, active, onClick }) {
  const { finding:f, cr } = c;
  const kind = f.layer === 'vvb_to_developer' ? f.id.split('-')[0] : 'CR';
  const kindMeta = { CAR:{ fg:'#991B1B', lbl:'Corrective action' }, CL:{ fg:'#92400E', lbl:'Clarification' }, FAR:{ fg:'#0C4A6E', lbl:'Forward action' }, CR:{ fg:'#7C5104', lbl:'Change request' } }[kind];
  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={{fontFamily:"'JetBrains Mono', monospace", fontSize:10, fontWeight:800, color:kindMeta.fg}}>{cr.id}</span>
        <span style={{fontSize:10, fontWeight:700, color:RV.faint}}>{kindMeta.lbl}</span>
        <span style={{marginLeft:'auto'}}><StatusChip status={f.status} developerView/></span>
      </div>
      <div style={{fontSize:13, fontWeight:800, color:RV.ink, lineHeight:1.35, marginBottom:4}}>{f.anchor.section_title}</div>
      <div style={{fontSize:11, color:RV.muted, display:'flex', justifyContent:'space-between'}}>
        <span style={{fontFamily:"'JetBrains Mono', monospace", color:RV.blue}}>{f.scope_document !== 'PD' ? `${(SCOPE_DOCS[f.scope_document] || {}).short || ''} ` : ''}§{f.anchor.section}</span>
        <span>{cr.due_days ? `Due in ${cr.due_days} days` : 'No due date'}</span>
      </div>
    </button>
  );
}

function ChangeRequestDetail({ c, review, dispatch, project }) {
  const { finding:f, cr, needsAnother } = c;
  const sec = sectionFor(f.anchor.field_id) || sectionOfFinding(review, f);
  const current = f.anchor.field_id ? latestVersion(review.versions, f.anchor.field_id) : null;
  const handedBack = !!cr.developer_handback;
  const editable = f.status === 'pending_developer';
  const [narrative, setNarrative] = React.useState(current ? (current.narrative || current.value) : (sec ? sec.narrative : ''));
  const [value, setValue] = React.useState(current ? current.value : '');
  const [docs, setDocs] = React.useState([]);
  const [note, setNote] = React.useState('');
  const [newDoc, setNewDoc] = React.useState('');
  React.useEffect(() => { setNarrative(current ? (current.narrative || current.value) : (sec ? sec.narrative : '')); setValue(current ? current.value : ''); setDocs([]); setNote(''); }, [f.id]);
  const changed = current ? narrative !== (current.narrative || current.value) || value !== current.value : narrative !== (sec ? sec.narrative : '');
  const prevRounds = f.rounds.filter(r => r.change_request && r.change_request.developer_handback && r !== c.round);
  const toggle = (id) => setDocs(d => d.includes(id) ? d.filter(x=>x!==id) : [...d, id]);
  const addDoc = () => { if (!newDoc.trim()) return; dispatch('addEvidence', { title:newDoc.trim(), filename:newDoc.trim().toLowerCase().replace(/[^a-z0-9]+/g,'-') + '.pdf' }); setNewDoc(''); };
  // pick up the id of a doc just added
  React.useEffect(() => { if (review._lastDoc && !docs.includes(review._lastDoc)) setDocs(d => [...d, review._lastDoc]); }, [review._lastDoc]);
  const kind = f.layer === 'vvb_to_developer' ? f.id.split('-')[0] : 'CR';
  return (
    <div style={{background:'#fff', border:`1px solid ${RV.line}`, borderRadius:10, overflow:'hidden'}}>
      <div style={{padding:'20px 24px', borderBottom:'1px solid #F3F4F6', background: editable ? '#FFF8E0' : RV.bg}}>
        <div style={{display:'flex', alignItems:'center', gap:10, marginBottom:8, flexWrap:'wrap'}}>
          <span style={{fontFamily:"'JetBrains Mono', monospace", fontSize:11, fontWeight:800, color:RV.ink, background:'#fff', padding:'3px 8px', borderRadius:6, border:`1px solid ${RV.line}`}}>{cr.id}</span>
          <StatusChip status={f.status} developerView/>
          {needsAnother && <Badge variant="amber" dot>Needs another change</Badge>}
          <span style={{fontSize:11, color:RV.muted}}>{cr.due_days ? `Due in ${cr.due_days} days` : 'Forward action, no due date'} · from Sarah Chen, SCS Global Services</span>
        </div>
        <h2 style={{fontSize:20, fontWeight:900, color:RV.ink, margin:'0 0 10px'}}>
          {kind === 'CR' ? 'Update' : kind === 'CAR' ? 'Correct' : kind === 'CL' ? 'Clarify' : 'Plan'}: {(SCOPE_DOCS[f.scope_document] || SCOPE_DOCS.PD).label} Section {f.anchor.section}, {f.anchor.section_title}
        </h2>
        <div style={{display:'flex', gap:8, alignItems:'center', flexWrap:'wrap'}}>
          <AnchorChip anchor={f.anchor} scope={f.scope_document}/>
          {f.program_rules.map((r,i)=><RuleChip key={i} rule={r}/>)}
        </div>
      </div>

      <div style={{padding:'20px 24px', borderBottom:'1px solid #F3F4F6'}}>
        <div style={{fontSize:10, fontWeight:800, textTransform:'uppercase', letterSpacing:'0.12em', color:RV.faint, marginBottom:8}}>What your VVB asked</div>
        <ResponseCard who="Sarah Chen, VVB" initials="SC" accent={RV.green} date={cr.date} title={`Change request ${cr.id}`} text={cr.note}/>
        {f.layer === 'vvb_to_developer' && (
          <div style={{marginTop:12}}><NumberedBlock title="Detail" items={f.issue} tone={RV.red}/></div>
        )}
      </div>

      {prevRounds.length > 0 && (
        <div style={{padding:'16px 24px', borderBottom:'1px solid #F3F4F6', background:RV.bg}}>
          <div style={{fontSize:10, fontWeight:800, textTransform:'uppercase', letterSpacing:'0.12em', color:RV.faint, marginBottom:8}}>Earlier rounds on this field</div>
          {prevRounds.map(r => (
            <div key={r.n} style={{fontSize:12, color:RV.muted, display:'flex', gap:10, alignItems:'center', marginBottom:4}}>
              <span style={{fontFamily:"'JetBrains Mono', monospace", fontWeight:800, color:RV.ink}}>{r.change_request.id}</span>
              <span>handed back {fmtDate(r.change_request.developer_handback.date)} as <span style={{fontFamily:"'JetBrains Mono', monospace", color:RV.blue}}>{r.change_request.developer_handback.field_version_id}</span></span>
              <Badge variant="blue">Accepted by VVB, registry asked for more</Badge>
            </div>
          ))}
        </div>
      )}

      <div style={{padding:'20px 24px'}}>
        <div style={{display:'flex', justifyContent:'space-between', alignItems:'baseline', marginBottom:8}}>
          <div style={{fontSize:10, fontWeight:800, textTransform:'uppercase', letterSpacing:'0.12em', color:RV.faint}}>The field</div>
          {current && <span style={{fontSize:11, color:RV.muted}}>Current <span style={{fontFamily:"'JetBrains Mono', monospace", color:RV.blue, fontWeight:800}}>{current.id}</span> · {current.author} · {fmtDate(current.date)}{current.hedera_anchor_id && <> · <HederaChip id={current.hedera_anchor_id}/></>}</span>}
        </div>

        {editable ? (
          <>
            {current && current.value && (
              <label style={{display:'block', marginBottom:10}}>
                <div style={{fontSize:11, fontWeight:800, color:RV.ink, marginBottom:4}}>Field value</div>
                <input value={value} onChange={e=>setValue(e.target.value)} style={{width:'100%', border:`1.5px solid ${RV.line}`, borderRadius:10, padding:'10px 12px', fontFamily:'inherit', fontSize:13, color:RV.ink, outline:'none', minHeight:40}}/>
              </label>
            )}
            <label style={{display:'block'}}>
              <div style={{fontSize:11, fontWeight:800, color:RV.ink, marginBottom:4}}>Section {f.anchor.section} text</div>
              <textarea value={narrative} onChange={e=>setNarrative(e.target.value)} style={{width:'100%', minHeight:120, border:`1.5px solid ${changed ? RV.gold : RV.line}`, borderRadius:10, padding:'10px 12px', fontFamily:'inherit', fontSize:13, lineHeight:1.6, color:RV.ink, outline:'none', resize:'vertical'}}/>
            </label>
            {changed && current && (
              <div style={{marginTop:12}}>
                <Redline before={current.narrative || current.value} after={narrative} labelBefore={`${current.id} (current)`} labelAfter={`v${current.version+1} (your edit)`}/>
              </div>
            )}

            <div style={{marginTop:16}}>
              <div style={{fontSize:10, fontWeight:800, textTransform:'uppercase', letterSpacing:'0.12em', color:RV.faint, marginBottom:8}}>Attach evidence (numbered documents)</div>
              <div style={{display:'flex', gap:6, flexWrap:'wrap', marginBottom:10}}>
                {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 style={{display:'flex', gap:8}}>
                <input value={newDoc} onChange={e=>setNewDoc(e.target.value)} onKeyDown={e=>{ if (e.key==='Enter') addDoc(); }} placeholder="Upload a new document: give it a title" style={{flex:1, border:`1.5px solid ${RV.line}`, borderRadius:10, padding:'8px 12px', fontFamily:'inherit', fontSize:13, color:RV.ink, outline:'none', minHeight:40}}/>
                <Btn kind="secondary" icon="upload" onClick={addDoc} disabled={!newDoc.trim()} style={{minHeight:40}}>Upload</Btn>
              </div>
            </div>

            <div style={{marginTop:16, border:`1.5px solid ${RV.gold}`, borderRadius:10, padding:14, background:'#FFFDF5'}}>
              <div style={{fontSize:12, fontWeight:900, color:RV.ink, marginBottom:8}}>Hand back to your VVB</div>
              <textarea value={note} onChange={e=>setNote(e.target.value)} placeholder="One or two sentences on what you changed and why." style={{width:'100%', minHeight:60, border:`1.5px solid ${RV.line}`, borderRadius:10, padding:'10px 12px', fontFamily:'inherit', fontSize:13, color:RV.ink, outline:'none', resize:'vertical', background:'#fff'}}/>
              <div style={{display:'flex', justifyContent:'space-between', alignItems:'center', marginTop:10, gap:10}}>
                <span style={{fontSize:11, color:RV.muted}}>Saving creates <span style={{fontFamily:"'JetBrains Mono', monospace", fontWeight:800, color:RV.blue}}>{f.anchor.field_id}@v{current ? current.version+1 : 1}</span>, anchored to Hedera. The earlier version stays on the record.</span>
                <Btn kind="primary" icon="arrowRight" disabled={!changed && docs.length === 0} onClick={()=>dispatch('handBack', { findingId:f.id, narrative, value, evidenceDocIds:docs, note: note || 'Updated as requested.' })} style={{minHeight:40}}>Save new version and hand back</Btn>
              </div>
            </div>
          </>
        ) : (
          <>
            <div style={{fontSize:14, lineHeight:1.7, color:RV.ink, padding:'12px 14px', background:RV.bg, border:`1px solid ${RV.line}`, borderRadius:10}}>{current ? (current.narrative || current.value) : (sec ? sec.narrative : '')}</div>
            {handedBack && (
              <div style={{marginTop:12}}>
                <ResponseCard who="You" initials="GK" accent={RV.gold} date={cr.developer_handback.date} title="Handed back" text={cr.developer_handback.note}>
                  <div style={{display:'flex', gap:6, flexWrap:'wrap', marginTop:8, alignItems:'center'}}>
                    <span style={{fontFamily:"'JetBrains Mono', monospace", fontSize:10, color:RV.blue, fontWeight:800, background:'#E8F4FC', padding:'2px 7px', borderRadius:4}}>{cr.developer_handback.field_version_id}</span>
                    {cr.developer_handback.evidence_doc_ids.map(id => <EvidenceChip key={id} id={id} evidence={review.evidence}/>)}
                  </div>
                </ResponseCard>
              </div>
            )}
            <div style={{marginTop:12}}>
              {f.status === 'closed'
                ? <PreviewBanner tone="gray">Accepted. Your VVB has verified this change.</PreviewBanner>
                : <PreviewBanner tone="blue">Handed back. Your VVB is reviewing the new version. You will hear from them if anything else is needed.</PreviewBanner>}
            </div>
          </>
        )}
      </div>
    </div>
  );
}

function VvbCommentsForDeveloper({ comments }) {
  if (!comments.length) return null;
  return (
    <Card padding={0} style={{marginBottom:18}}>
      <div style={{padding:'12px 20px', borderBottom:'1px solid #F3F4F6'}}>
        <SectionHeader eyebrow="From your VVB" title={`${comments.length} comment${comments.length>1?'s':''} on your documents`} eyebrowColor={RV.green} tail="Comments are guidance. Anything that must change arrives as a change request below."/>
      </div>
      <div style={{padding:'6px 20px 12px'}}>
        {comments.slice().reverse().map((c, i, arr) => (
          <div key={c.id} style={{display:'grid', gridTemplateColumns:'150px 1fr 110px', gap:12, padding:'10px 0', borderBottom: i < arr.length-1 ? '1px dashed #F3F4F6' : 'none', alignItems:'start', fontSize:12}}>
            <span><span style={{fontFamily:"'JetBrains Mono', monospace", color:RV.blue, fontWeight:800}}>{c.doc} §{c.section}</span><div style={{fontSize:11, color:RV.muted, marginTop:2}}>{c.author}</div></span>
            <span style={{color:RV.ink, lineHeight:1.55}}>{c.text}</span>
            <span style={{color:RV.faint, fontFamily:"'JetBrains Mono', monospace", textAlign:'right'}}>{fmtDate(c.date)}</span>
          </div>
        ))}
      </div>
    </Card>
  );
}

window.ChangeRequestsView = ChangeRequestsView;
