/* global React */
const { useState } = React;

// ─────────── Reviewer Login ───────────
const ReviewerLogin = ({ onDone }) => (
  <div className="center-wrap">
    <div className="center-card rise" style={{maxWidth:440}}>
      <div className="eyebrow" style={{marginBottom:16, color:'var(--ink-3)'}}>Reviewer console</div>
      <h2 className="h-section">Welcome back, J.</h2>
      <p className="muted" style={{marginTop:8, marginBottom:20, fontSize:13.5}}>Sign in with your state SSO. MFA required — this is a HIPAA-regulated environment.</p>
      <Btn variant="primary" size="lg" block onClick={onDone}><Icon name="shield" size={15}/> Continue with State SSO</Btn>
      <div className="divider-x">Alt</div>
      <Field label="State-issued email"><input className="input" defaultValue="j.delacruz@dss.state.gov"/></Field>
      <Field label="Password"><input className="input" type="password" defaultValue="••••••••••"/></Field>
      <Btn variant="secondary" size="lg" block style={{marginTop:14}} onClick={onDone}>Sign in</Btn>
      <div className="flag info" style={{marginTop:18, fontSize:12.5}}>
        <div className="ico"><Icon name="info" size={14}/></div>
        <div>All reviewer actions are logged. Session times out after 15 min of inactivity.</div>
      </div>
    </div>
  </div>
);

// ─────────── Reviewer sidebar ───────────
const ReviewerSidebar = ({ view, setView }) => {
  const items = [
    { k:'queue', label:'My queue', icon:'list', count:14, group:'Cases' },
    { k:'unassigned', label:'Unassigned', icon:'folder', count:42, group:'Cases' },
    { k:'waiting', label:'Waiting on applicant', icon:'clock', count:7, group:'Cases' },
    { k:'escalated', label:'Escalated', icon:'flag', count:2, group:'Cases' },
    { k:'workspace', label:'Open case', icon:'doc', group:'Active' },
    { k:'diff', label:'Answers vs docs', icon:'balance', group:'Active' },
    { k:'docreview', label:'Document review', icon:'docCheck', group:'Active' },
    { k:'audit', label:'Audit timeline', icon:'clock', group:'Active' },
    { k:'analytics', label:'Analytics', icon:'activity', group:'Reports' },
  ];
  let last = null;
  return (
    <aside className="sidebar">
      {items.map(it => {
        const grp = it.group !== last ? <div key={it.group} className="sidebar-section">{it.group}</div> : null;
        last = it.group;
        return <>
          {grp}
          <div key={it.k} className={`nav-item ${view===it.k?'on':''}`} onClick={()=>setView(it.k)}>
            <Icon name={it.icon} size={15}/> <span>{it.label}</span>
            {it.count != null && <span className="count">{it.count}</span>}
          </div>
        </>;
      })}
      <div style={{marginTop:'auto', padding:'12px 10px', borderTop:'1px solid var(--line)', fontSize:12, color:'var(--ink-3)'}}>
        <div style={{display:'flex', alignItems:'center', gap:10}}>
          <div style={{width:30, height:30, borderRadius:'50%', background:'var(--accent-soft)', color:'var(--accent-ink)', display:'grid', placeItems:'center', fontSize:11, fontWeight:600}}>JD</div>
          <div style={{flex:1, minWidth:0}}>
            <div style={{color:'var(--ink)', fontWeight:500, fontSize:12.5}}>J. Delacruz</div>
            <div className="tiny">SSDI specialist · L2</div>
          </div>
          <button className="icon-btn"><Icon name="logout" size={14}/></button>
        </div>
      </div>
    </aside>
  );
};

// ─────────── Queue ───────────
const ReviewerQueue = ({ onOpen }) => {
  const [filter, setFilter] = useState('all');
  const rows = [
    { id:'GE-2026-4782', app:'Maria L. Ramirez', type:'SSDI', status:'In review', age:'2h', priority:'—', flags:2, progress:80, due:'Apr 27' },
    { id:'GE-2026-4779', app:'Samuel Okafor', type:'VA Disability', status:'Needs info', age:'1d', priority:'High', flags:3, progress:55, due:'Apr 25' },
    { id:'GE-2026-4761', app:'Jennifer H. Park', type:'SSI', status:'Ready', age:'4h', priority:'—', flags:0, progress:100, due:'Apr 24' },
    { id:'GE-2026-4758', app:'Marcus D. Brown', type:'SSDI', status:'Overdue', age:'3d', priority:'Urgent', flags:4, progress:65, due:'Apr 22' },
    { id:'GE-2026-4742', app:'Aisha R. Farah', type:'VA Healthcare', status:'In review', age:'6h', priority:'—', flags:0, progress:45, due:'Apr 28' },
    { id:'GE-2026-4729', app:'Thomas K. Lin', type:'SSDI', status:'Waiting', age:'5d', priority:'—', flags:1, progress:35, due:'Apr 29' },
    { id:'GE-2026-4718', app:'Rosa E. Castillo', type:'SSI', status:'Ready', age:'1d', priority:'—', flags:0, progress:100, due:'Apr 26' },
    { id:'GE-2026-4702', app:'David M. Cho', type:'SSDI', status:'In review', age:'2d', priority:'—', flags:1, progress:72, due:'Apr 30' },
  ];
  const statusBadge = (s) => {
    if (s === 'Overdue') return <Badge variant="danger" dot>{s}</Badge>;
    if (s === 'Ready') return <Badge variant="accent" dot>{s}</Badge>;
    if (s === 'Needs info') return <Badge variant="warn" dot>{s}</Badge>;
    if (s === 'Waiting') return <Badge>{s}</Badge>;
    return <Badge variant="info" dot>{s}</Badge>;
  };
  return (
    <div className="main-col">
      <div className="page-head">
        <div>
          <h1>My queue</h1>
          <p className="lead">14 cases assigned · 2 overdue · average age 18h</p>
        </div>
        <div style={{display:'flex', gap:8, alignItems:'center'}}>
          <div className="seg" style={{padding:2}}>
            {['all','mine','team'].map(f => (
              <button key={f} className={filter===f?'on':''} onClick={()=>setFilter(f)} style={{padding:'6px 12px', fontSize:12, fontWeight:500, borderRadius:6}}>{f[0].toUpperCase()+f.slice(1)}</button>
            ))}
          </div>
          <div style={{position:'relative'}}>
            <Icon name="search" size={14} style={{position:'absolute', left:10, top:'50%', transform:'translateY(-50%)', color:'var(--ink-3)'}}/>
            <input className="input" placeholder="Search case or name…" style={{paddingLeft:32, width:240}}/>
          </div>
          <Btn variant="secondary" size="sm"><Icon name="filter" size={13}/> Filters</Btn>
        </div>
      </div>

      <div className="page-body">
        <div className="grid-4" style={{marginBottom:20}}>
          <StatCard label="Open cases" value="14" note="2 overdue"/>
          <StatCard label="Ready to approve" value="2" delta="+1" deltaDir="up" note="today"/>
          <StatCard label="Avg review time" value="2.1d" delta="−14%" deltaDir="up" note="vs team"/>
          <StatCard label="Backlog risk" value="Low" note="SLA 96%"/>
        </div>

        <div className="card" style={{overflow:'hidden'}}>
          <table className="table">
            <thead>
              <tr>
                <th>Case</th><th>Applicant</th><th>Type</th><th>Status</th><th>Priority</th><th>Flags</th><th>Progress</th><th>Due</th><th></th>
              </tr>
            </thead>
            <tbody>
              {rows.map((r,i) => (
                <tr key={r.id} className={i===0?'sel':''} onClick={onOpen}>
                  <td className="mono" style={{fontSize:12, color:'var(--ink-2)'}}>{r.id}</td>
                  <td style={{fontWeight:500}}>{r.app}</td>
                  <td><Badge>{r.type}</Badge></td>
                  <td>{statusBadge(r.status)}</td>
                  <td style={{color: r.priority==='Urgent'?'var(--danger)':r.priority==='High'?'var(--warn)':'var(--ink-3)', fontSize:12.5, fontWeight:500}}>{r.priority}</td>
                  <td>{r.flags > 0 ? <Badge variant={r.flags>2?'danger':'warn'}>{r.flags}</Badge> : <span style={{color:'var(--ink-4)'}}>—</span>}</td>
                  <td style={{minWidth:140}}>
                    <div style={{display:'flex', alignItems:'center', gap:10}}>
                      <div style={{flex:1}}><Progress value={r.progress}/></div>
                      <span className="mono tiny" style={{width:32, textAlign:'right'}}>{r.progress}%</span>
                    </div>
                  </td>
                  <td className="tiny" style={{color: r.status==='Overdue'?'var(--danger)':'var(--ink-3)'}}>{r.due}</td>
                  <td><button className="icon-btn"><Icon name="chev" size={14}/></button></td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>
      </div>
    </div>
  );
};

// ─────────── Reviewer Case Workspace ───────────
const ReviewerWorkspace = ({ onDiff, onDocReview, onRequestInfo, onApprove, onEscalate, onAudit }) => {
  const [tab, setTab] = useState('answers');
  return (
    <div className="main-col" style={{padding:0}}>
      {/* Case header */}
      <div style={{padding:'18px 28px', borderBottom:'1px solid var(--line)', background:'var(--bg-elev)'}}>
        <div style={{display:'flex', justifyContent:'space-between', alignItems:'flex-start', gap:20}}>
          <div>
            <div style={{display:'flex', alignItems:'center', gap:10, marginBottom:6}}>
              <span className="mono tiny" style={{color:'var(--ink-3)', letterSpacing:'.14em', textTransform:'uppercase'}}>GE-2026-4782</span>
              <Badge variant="info" dot>In review</Badge>
              <Badge variant="warn" dot>2 flags</Badge>
              <Badge><Icon name="balance" size={10}/> SSDI</Badge>
            </div>
            <div style={{display:'flex', alignItems:'center', gap:12}}>
              <div style={{width:38, height:38, borderRadius:'50%', background:'var(--accent-soft)', color:'var(--accent-ink)', display:'grid', placeItems:'center', fontWeight:600, fontSize:13}}>MR</div>
              <div>
                <div style={{fontFamily:'var(--serif)', fontSize:24}}>Maria L. Ramirez</div>
                <div className="tiny">46 · Brooklyn, NY · EN · filed 2 days ago · due Apr 27</div>
              </div>
            </div>
          </div>
          <div style={{display:'flex', gap:8}}>
            <Btn variant="secondary" size="sm" onClick={onRequestInfo}><Icon name="chat" size={13}/> Request info</Btn>
            <Btn variant="secondary" size="sm" onClick={onEscalate}><Icon name="flag" size={13}/> Escalate</Btn>
            <Btn variant="accent" size="sm" onClick={onApprove}><Icon name="check" size={13}/> Approve</Btn>
          </div>
        </div>

        <div style={{display:'flex', gap:16, marginTop:16, fontSize:12.5, color:'var(--ink-3)'}}>
          <span><Icon name="mail" size={12} style={{verticalAlign:'-2px'}}/> maria.r@outlook.com</span>
          <span><Icon name="phone" size={12} style={{verticalAlign:'-2px'}}/> (347) 555-0132</span>
          <span><Icon name="calendar" size={12} style={{verticalAlign:'-2px'}}/> DOB Jun 12, 1979</span>
          <span><Icon name="doc" size={12} style={{verticalAlign:'-2px'}}/> 8 documents</span>
          <span><Icon name="clock" size={12} style={{verticalAlign:'-2px'}}/> 14 sections · 100%</span>
        </div>

        <div style={{marginTop:18, display:'flex', gap:2, borderBottom:'0'}}>
          {[
            ['answers','Applicant answers'],
            ['diff','Answers vs documents'],
            ['docs','Documents'],
            ['ai','AI activity'],
            ['timeline','Timeline'],
          ].map(([k, label]) => (
            <button
              key={k}
              onClick={()=> k==='diff' ? onDiff() : k==='docs' ? onDocReview() : k==='timeline' ? onAudit() : setTab(k)}
              style={{
                padding:'10px 14px', fontSize:13, fontWeight:500,
                color: tab===k ? 'var(--ink)' : 'var(--ink-3)',
                borderBottom: tab===k ? '2px solid var(--accent)' : '2px solid transparent',
                marginBottom:-1, cursor:'pointer'
              }}
            >{label}</button>
          ))}
        </div>
      </div>

      {/* Body */}
      <div style={{padding:'22px 28px', overflow:'auto', flex:1, display:'grid', gridTemplateColumns:'1fr 340px', gap:20}}>
        <div>
          {/* AI insights */}
          <div className="flag info" style={{marginBottom:16}}>
            <div className="ico"><Icon name="sparkle" size={15}/></div>
            <div>
              <strong>AI summary (96% confidence):</strong> Applicant reports fibromyalgia with functional onset Mar 2023. Medical documentation covers Feb 2023–Nov 2024 continuously. Work history consistent. <strong>Flag:</strong> onset date mismatch between intake Q-7 (March 2023) and Q-22 (Summer 2022). <a style={{color:'inherit', textDecoration:'underline'}} onClick={onDiff}>Open diff →</a>
            </div>
          </div>

          {INTAKE_SECTIONS.slice(0,3).map((sec, si) => (
            <div key={sec.k} className="card" style={{marginBottom:14}}>
              <div style={{padding:'12px 18px', borderBottom:'1px solid var(--line)', display:'flex', justifyContent:'space-between', alignItems:'center'}}>
                <div style={{display:'flex', alignItems:'center', gap:10}}>
                  <span className="mono tiny" style={{color:'var(--ink-4)', letterSpacing:'.12em', textTransform:'uppercase'}}>Section {si+1}</span>
                  <span style={{fontFamily:'var(--serif)', fontSize:18}}>{sec.title}</span>
                </div>
                <Badge variant="accent">Complete</Badge>
              </div>
              <div style={{padding:'14px 18px'}}>
                <div className="grid-2" style={{gap:14}}>
                  {sec.steps.slice(0,4).map((step, i) => (
                    <div key={i} style={{paddingBottom:10, borderBottom:'1px dotted var(--line)'}}>
                      <div className="tiny" style={{textTransform:'uppercase', letterSpacing:'.08em', fontFamily:'var(--mono)', fontSize:10, color:'var(--ink-3)'}}>{step}</div>
                      <div style={{fontSize:13.5, marginTop:2, fontWeight:500}}>{['Maria L. Ramirez','Jun 12, 1979','Fibromyalgia','March 2023','Brooklyn, NY','(347) 555-0132'][i] || '—'}</div>
                      {i===3 && si===1 && <div className="tiny" style={{marginTop:4, color:'var(--warn)'}}><Icon name="warn" size={10}/> Conflicts with Q-22</div>}
                    </div>
                  ))}
                </div>
              </div>
            </div>
          ))}
        </div>

        {/* Right rail */}
        <aside className="col" style={{gap:14, position:'sticky', top:0, alignSelf:'start'}}>
          <div className="card card-pad">
            <div className="mono tiny" style={{color:'var(--ink-4)', letterSpacing:'.14em', textTransform:'uppercase', marginBottom:10}}>Quick actions</div>
            <div className="col" style={{gap:6}}>
              <Btn variant="secondary" size="sm" block style={{justifyContent:'flex-start'}}><Icon name="pin" size={13}/> Pin this case</Btn>
              <Btn variant="secondary" size="sm" block style={{justifyContent:'flex-start'}}><Icon name="users" size={13}/> Reassign</Btn>
              <Btn variant="secondary" size="sm" block style={{justifyContent:'flex-start'}}><Icon name="print" size={13}/> Print draft packet</Btn>
            </div>
          </div>

          <div className="card card-pad">
            <div className="mono tiny" style={{color:'var(--ink-4)', letterSpacing:'.14em', textTransform:'uppercase', marginBottom:10}}>Flags (2)</div>
            <div className="col" style={{gap:10}}>
              <div style={{padding:'10px 12px', background:'var(--warn-soft)', borderRadius:8, fontSize:12.5}}>
                <div style={{fontWeight:500, marginBottom:2}}>Date mismatch</div>
                <div className="tiny">Symptom onset: Mar 2023 vs Summer 2022 · <a style={{color:'var(--accent-ink)'}} onClick={onDiff}>Resolve</a></div>
              </div>
              <div style={{padding:'10px 12px', background:'var(--warn-soft)', borderRadius:8, fontSize:12.5}}>
                <div style={{fontWeight:500, marginBottom:2}}>Low-quality image</div>
                <div className="tiny">IMG_4218.heic · resolved Tue</div>
              </div>
            </div>
          </div>

          <div className="card card-pad">
            <div className="mono tiny" style={{color:'var(--ink-4)', letterSpacing:'.14em', textTransform:'uppercase', marginBottom:10}}>Private notes</div>
            <textarea className="textarea" placeholder="Notes only you and supervisors can see…" defaultValue="Strong SSDI candidate based on docs. Waiting on onset clarification from applicant."/>
          </div>
        </aside>
      </div>
    </div>
  );
};

// ─────────── Diff view ───────────
const ReviewerDiff = ({ onBack }) => {
  return (
    <div className="main-col">
      <div className="page-head">
        <div>
          <div style={{display:'flex', gap:10, alignItems:'center', marginBottom:6}}>
            <button className="icon-btn" onClick={onBack}><Icon name="arrowL" size={16}/></button>
            <span className="mono tiny" style={{color:'var(--ink-3)', letterSpacing:'.14em', textTransform:'uppercase'}}>GE-2026-4782 · M. Ramirez</span>
          </div>
          <h1>Answers vs documents</h1>
          <p className="lead">Cross-check what the applicant typed against what their files actually say.</p>
        </div>
        <div style={{display:'flex', gap:8}}>
          <Btn variant="secondary" size="sm"><Icon name="filter" size={13}/> Only mismatches</Btn>
          <Btn variant="accent" size="sm"><Icon name="chat" size={13}/> Request clarification</Btn>
        </div>
      </div>
      <div className="page-body">
        <div className="grid-4" style={{marginBottom:20}}>
          <StatCard label="Total fields checked" value="42"/>
          <StatCard label="Matches" value="38" note="auto-verified"/>
          <StatCard label="Mismatches" value="2" note="need reviewer action"/>
          <StatCard label="Unsupported by docs" value="2" note="OK but manual check"/>
        </div>

        <div className="card">
          {[
            { q:'Date of birth', a:'Jun 12, 1979', doc:'1979-06-12', docSrc:'DL_Maria_R.pdf', match:true },
            { q:'Symptom onset', a:'March 2023', doc:'"First widespread pain flare: Feb 2023" — Dr. Patel notes', docSrc:'Dr_Patel_Visit_2024-11.pdf', match:false, severity:'mismatch' },
            { q:'Primary diagnosis', a:'Fibromyalgia', doc:'M79.7 Fibromyalgia (confirmed)', docSrc:'ICD_Diagnosis_Letter.pdf', match:true },
            { q:'Last employer', a:'Riverside Medical Center', doc:'W2 issuer: Riverside Medical Ctr Inc.', docSrc:'W2_2024.pdf', match:true },
            { q:'Employment end date', a:'March 2023', doc:'Last paystub: Mar 31, 2023', docSrc:'W2_2024.pdf', match:true },
            { q:'Primary care doctor', a:'Dr. A. Patel', doc:'Not attested in uploaded records', docSrc:'—', match:null, severity:'unsupported' },
          ].map((r, i) => (
            <div key={i} className="diff-row">
              <div className="diff-q">Q-{String(i+7).padStart(2,'0')} · {r.q}</div>
              <div className={`diff-cell ${r.match===true?'match':r.match===false?'mismatch':''}`}>
                <span className="lbl">Applicant answer</span>
                <div style={{fontSize:13.5}}>{r.a}</div>
              </div>
              <div className={`diff-cell ${r.match===true?'match':r.match===false?'mismatch':''}`} style={r.match===null?{borderStyle:'dashed'}:null}>
                <span className="lbl" style={{display:'flex', justifyContent:'space-between'}}>
                  <span>Extracted from {r.docSrc !== '—' ? r.docSrc : 'n/a'}</span>
                  {r.match===true && <span style={{color:'var(--accent)'}}><Icon name="check" size={10} stroke={3}/> Match</span>}
                  {r.match===false && <span style={{color:'var(--warn)'}}><Icon name="warn" size={10}/> Mismatch</span>}
                  {r.match===null && <span style={{color:'var(--ink-3)'}}>No source</span>}
                </span>
                <div style={{fontSize:13}}>{r.doc}</div>
                {r.match === false && (
                  <div style={{marginTop:8, display:'flex', gap:6}}>
                    <Btn variant="accent" size="sm">Accept doc value</Btn>
                    <Btn variant="secondary" size="sm">Keep applicant's</Btn>
                    <Btn variant="ghost" size="sm">Ask applicant</Btn>
                  </div>
                )}
              </div>
            </div>
          ))}
        </div>
      </div>
    </div>
  );
};

// ─────────── Document Review Panel ───────────
const ReviewerDocReview = ({ onBack }) => {
  const [sel, setSel] = useState(0);
  const docs = [
    { name:'Dr_Patel_Visit_2024-11.pdf', type:'PDF', size:'1.2 MB', status:'clean', extracts:12 },
    { name:'MRI_Report.jpg', type:'JPG', size:'3.8 MB', status:'clean', extracts:5 },
    { name:'Dr_Patel_Visit_2024-11_v2.pdf', type:'PDF', size:'1.4 MB', status:'clean', extracts:14 },
    { name:'W2_2024.pdf', type:'PDF', size:'0.4 MB', status:'clean', extracts:8 },
    { name:'DL_Maria_R.pdf', type:'PDF', size:'0.3 MB', status:'clean', extracts:6 },
    { name:'ICD_Diagnosis_Letter.pdf', type:'PDF', size:'0.9 MB', status:'clean', extracts:3 },
  ];
  return (
    <div className="main-col">
      <div className="page-head">
        <div>
          <div style={{display:'flex', gap:10, alignItems:'center', marginBottom:6}}>
            <button className="icon-btn" onClick={onBack}><Icon name="arrowL" size={16}/></button>
            <span className="mono tiny" style={{color:'var(--ink-3)', letterSpacing:'.14em', textTransform:'uppercase'}}>GE-2026-4782 · documents</span>
          </div>
          <h1>Document review</h1>
          <p className="lead">6 files · all virus-scanned · 48 fields extracted</p>
        </div>
      </div>
      <div className="page-body" style={{padding:0}}>
        <div className="split-3" style={{padding:'20px 28px', height:'calc(100vh - 52px - 120px)'}}>
          <div className="card" style={{padding:0, overflow:'auto'}}>
            <div style={{padding:'10px 14px', borderBottom:'1px solid var(--line)', display:'flex', justifyContent:'space-between', alignItems:'center'}}>
              <span className="mono tiny" style={{color:'var(--ink-3)', letterSpacing:'.12em', textTransform:'uppercase'}}>Files</span>
              <Btn variant="ghost" size="sm"><Icon name="plus" size={12}/></Btn>
            </div>
            {docs.map((d,i) => (
              <button key={i} onClick={()=>setSel(i)} style={{
                width:'100%', textAlign:'left', padding:'10px 14px',
                borderBottom: i<docs.length-1?'1px solid var(--line)':'0',
                background: sel===i ? 'var(--accent-soft)' : 'transparent',
                color: sel===i ? 'var(--accent-ink)' : 'var(--ink)',
                display:'flex', gap:10, alignItems:'center', cursor:'pointer'
              }}>
                <div className="doc-ico" style={{width:30, height:36, fontSize:9}}>{d.type}</div>
                <div style={{flex:1, minWidth:0}}>
                  <div style={{fontSize:12.5, fontWeight:500, whiteSpace:'nowrap', overflow:'hidden', textOverflow:'ellipsis'}}>{d.name}</div>
                  <div className="tiny">{d.size} · {d.extracts} fields</div>
                </div>
                <Icon name="check" size={12} style={{color:'var(--accent)'}}/>
              </button>
            ))}
          </div>

          <div className="card" style={{overflow:'hidden', display:'flex', flexDirection:'column'}}>
            <div style={{padding:'10px 14px', borderBottom:'1px solid var(--line)', display:'flex', justifyContent:'space-between', alignItems:'center'}}>
              <div style={{display:'flex', gap:10, alignItems:'center'}}>
                <span className="mono tiny" style={{color:'var(--ink-3)', letterSpacing:'.12em', textTransform:'uppercase'}}>{docs[sel].name}</span>
              </div>
              <div style={{display:'flex', gap:4}}>
                <button className="icon-btn"><Icon name="minus" size={14}/></button>
                <button className="icon-btn"><Icon name="plus" size={14}/></button>
                <button className="icon-btn"><Icon name="download" size={14}/></button>
              </div>
            </div>
            <div style={{flex:1, overflow:'auto', padding:22, background:'var(--bg-sunk)', display:'grid', placeItems:'start center'}}>
              <div style={{
                width: '90%', maxWidth:520, aspectRatio:'8.5/11',
                background:'var(--bg-elev)', border:'1px solid var(--line)',
                boxShadow:'var(--shadow-md)', position:'relative', padding:'36px 40px',
                fontFamily:'var(--serif)', lineHeight:1.5
              }}>
                <div style={{textAlign:'right', fontSize:10, fontFamily:'var(--mono)', color:'var(--ink-3)', marginBottom:12}}>Dr. A. Patel, MD · Riverside Medical</div>
                <div style={{fontSize:18, marginBottom:14}}>Patient Visit Summary</div>
                <div className="tiny" style={{color:'var(--ink-2)', lineHeight:1.6, fontFamily:'var(--sans)'}}>
                  Patient: <mark style={{background:'oklch(94% 0.08 155)', padding:'1px 3px', borderRadius:2}}>Maria L. Ramirez</mark><br/>
                  DOB: <mark style={{background:'oklch(94% 0.08 155)', padding:'1px 3px', borderRadius:2}}>06/12/1979</mark><br/>
                  Visit date: 11/22/2024<br/><br/>
                  Chief complaint: Widespread body pain, cognitive difficulties, chronic fatigue. Patient reports first widespread pain flare in <mark style={{background:'oklch(94% 0.1 70)', padding:'1px 3px', borderRadius:2}}>February 2023</mark>, with continuous symptoms since.<br/><br/>
                  Assessment: <mark style={{background:'oklch(94% 0.08 155)', padding:'1px 3px', borderRadius:2}}>Fibromyalgia (M79.7)</mark> — consistent with ACR 2016 criteria. Widespread pain index 14/19.<br/><br/>
                  Plan: Continue pregabalin 75mg BID. Refer to pain management. Follow-up in 3 months.
                </div>
              </div>
            </div>
            <div style={{padding:'8px 14px', borderTop:'1px solid var(--line)', display:'flex', justifyContent:'space-between', fontSize:12, color:'var(--ink-3)'}}>
              <span>Page 1 of 2</span>
              <span className="mono">OCR confidence: 97%</span>
            </div>
          </div>

          <aside className="card" style={{padding:0, overflow:'auto'}}>
            <div style={{padding:'10px 14px', borderBottom:'1px solid var(--line)'}}>
              <span className="mono tiny" style={{color:'var(--ink-3)', letterSpacing:'.12em', textTransform:'uppercase'}}>Extracted fields</span>
            </div>
            <div style={{padding:'6px 14px'}}>
              {[
                ['Patient name','Maria L. Ramirez', 98],
                ['DOB','06/12/1979', 99],
                ['Diagnosis','Fibromyalgia (M79.7)', 96],
                ['Onset','February 2023', 94],
                ['Provider','Dr. A. Patel, MD', 99],
                ['Visit date','Nov 22, 2024', 99],
                ['Medication','Pregabalin 75mg BID', 91],
              ].map(([k,v,c], i) => (
                <div key={i} style={{padding:'10px 0', borderBottom: i<6?'1px solid var(--line)':'0'}}>
                  <div className="tiny" style={{textTransform:'uppercase', letterSpacing:'.08em', fontFamily:'var(--mono)', fontSize:10, color:'var(--ink-3)'}}>{k}</div>
                  <div style={{display:'flex', justifyContent:'space-between', marginTop:3}}>
                    <div style={{fontSize:13, fontWeight:500}}>{v}</div>
                    <span className="mono tiny" style={{color: c>95?'var(--accent)':'var(--warn)'}}>{c}%</span>
                  </div>
                </div>
              ))}
            </div>
            <div style={{padding:'10px 14px', borderTop:'1px solid var(--line)'}}>
              <div className="mono tiny" style={{color:'var(--ink-3)', letterSpacing:'.12em', textTransform:'uppercase', marginBottom:8}}>Reviewer notes</div>
              <textarea className="textarea" style={{fontSize:12.5}} placeholder="Add a note about this document…"/>
              <div style={{display:'flex', gap:6, marginTop:8}}>
                <Btn variant="accent" size="sm" block><Icon name="check" size={12}/> Accept file</Btn>
                <Btn variant="secondary" size="sm"><Icon name="flag" size={12}/></Btn>
              </div>
            </div>
          </aside>
        </div>
      </div>
    </div>
  );
};

// ─────────── Request More Info modal ───────────
const RequestInfoModal = ({ onClose }) => {
  const [reason, setReason] = useState('date_mismatch');
  return (
    <Modal title="Request more information" onClose={onClose} wide footer={<>
      <Btn variant="ghost" onClick={onClose}>Cancel</Btn>
      <Btn variant="accent" onClick={onClose}><Icon name="send" size={13}/> Send to applicant</Btn>
    </>}>
      <p className="muted" style={{marginBottom:14, fontSize:13}}>This message will appear in Maria\'s tasks and send her an email. She can\'t progress until she responds.</p>

      <Field label="Reason category">
        <div className="grid-2" style={{gap:8}}>
          {[
            ['date_mismatch','Date conflict'],
            ['missing_doc','Missing document'],
            ['quality','Quality issue'],
            ['clarity','Need clarification'],
          ].map(([k, label]) => (
            <button key={k} className={`option-tile ${reason===k?'on':''}`} style={{padding:'10px 12px', fontSize:13}} onClick={()=>setReason(k)}>{label}</button>
          ))}
        </div>
      </Field>

      <div style={{marginTop:14}}>
        <Field label="Which question is this about?">
          <select className="select"><option>Q-07 · Symptom onset date</option><option>Q-14 · Medications</option></select>
        </Field>
      </div>

      <div style={{marginTop:14}}>
        <Field label="Message to applicant" hint="Write in plain language — the applicant will see this exactly.">
          <textarea className="textarea" rows={4} defaultValue="Hi Maria — in your intake, you mentioned both 'March 2023' and 'Summer 2022' as the time your symptoms started affecting you. Could you pick whichever feels most accurate? An approximate date is perfectly fine."/>
        </Field>
      </div>

      <label className="check" style={{marginTop:14}}>
        <input type="checkbox" defaultChecked/>
        <span>Pause review timer until applicant responds</span>
      </label>
    </Modal>
  );
};

// ─────────── Approve modal ───────────
const ApproveModal = ({ onClose, onDone }) => {
  return (
    <Modal title="Approve & file with SSA" onClose={onClose} footer={<>
      <Btn variant="ghost" onClick={onClose}>Cancel</Btn>
      <Btn variant="accent" onClick={onDone}><Icon name="check" size={13}/> Approve case</Btn>
    </>}>
      <div className="flag accent" style={{marginBottom:14}}>
        <div className="ico"><Icon name="shieldCheck" size={15}/></div>
        <div>You\'re approving case <strong className="mono">GE-2026-4782</strong> for M. Ramirez. Once approved, the packet is queued for SSA submission at the next business hour.</div>
      </div>
      <Field label="Justification (required, permanent record)" hint="Explain in 1–2 sentences why this case meets approval criteria.">
        <textarea className="textarea" rows={3} defaultValue="All fields are supported by uploaded documentation. One date conflict was resolved by applicant. Medical records are continuous over 20+ months. Work history verified against W-2."/>
      </Field>
      <div style={{marginTop:14}}>
        <Field label="Confidence">
          <div className="seg" style={{padding:2}}>
            <button className="on">High</button>
            <button>Medium</button>
            <button>Low (escalate instead)</button>
          </div>
        </Field>
      </div>
      <label className="check" style={{marginTop:14}}>
        <input type="checkbox" defaultChecked/>
        <span>I have verified applicant identity and all required documents are present.</span>
      </label>
    </Modal>
  );
};

// ─────────── Escalate modal ───────────
const EscalateModal = ({ onClose }) => (
  <Modal title="Escalate to supervisor" onClose={onClose} footer={<>
    <Btn variant="ghost" onClick={onClose}>Cancel</Btn>
    <Btn variant="primary" onClick={onClose} style={{background:'var(--warn)', color:'#fff'}}><Icon name="flag" size={13}/> Escalate case</Btn>
  </>}>
    <Field label="Escalate to">
      <select className="select">
        <option>A. Sokolov · Senior Reviewer (SSDI) — 4 cases queued</option>
        <option>M. Reeves · Supervisor — 12 cases queued</option>
        <option>Medical Board review — 2d turnaround</option>
      </select>
    </Field>
    <div style={{marginTop:14}}>
      <Field label="Reason for escalation (required)">
        <textarea className="textarea" rows={3} placeholder="What needs senior attention?"/>
      </Field>
    </div>
    <div style={{marginTop:14}}>
      <Field label="Priority">
        <div className="seg" style={{padding:2}}>
          <button className="on">Normal</button>
          <button>High</button>
          <button>Urgent</button>
        </div>
      </Field>
    </div>
  </Modal>
);

// ─────────── Audit Timeline (Reviewer view) ───────────
const ReviewerAudit = ({ onBack }) => (
  <div className="main-col">
    <div className="page-head">
      <div>
        <div style={{display:'flex', gap:10, alignItems:'center', marginBottom:6}}>
          <button className="icon-btn" onClick={onBack}><Icon name="arrowL" size={16}/></button>
          <span className="mono tiny" style={{color:'var(--ink-3)', letterSpacing:'.14em', textTransform:'uppercase'}}>GE-2026-4782 · audit timeline</span>
        </div>
        <h1>Full case audit</h1>
        <p className="lead">Every action — human, AI, and system — timestamped and immutable.</p>
      </div>
      <div style={{display:'flex', gap:8}}>
        <Btn variant="secondary" size="sm"><Icon name="filter" size={13}/> Filter: All events</Btn>
        <Btn variant="secondary" size="sm"><Icon name="download" size={13}/> Export CSV</Btn>
      </div>
    </div>
    <div className="page-body">
      <div className="card card-pad">
        <div className="timeline">
          {[
            ['2026-04-23 14:14:02', 'J.Delacruz', 'flagged date mismatch Q-07 vs Q-22', 'warn'],
            ['2026-04-23 14:13:41', 'AI · claude-extract-v3', 'detected inconsistency (conf 0.91): "March 2023" vs "Summer 2022"', 'ai'],
            ['2026-04-23 11:02:15', 'system', 'case assigned to J.Delacruz (auto — SSDI skill match)', ''],
            ['2026-04-22 17:40:09', 'maria.r@...', 'uploaded Dr_Patel_Visit_2024-11_v2.pdf (1.4 MB)', ''],
            ['2026-04-22 17:40:01', 'system', 'virus-scan PASS · OCR initiated', ''],
            ['2026-04-22 17:12:55', 'AI · vision-qa-v2', 'flagged IMG_4218.heic quality score 0.42 (threshold 0.7)', 'ai'],
            ['2026-04-22 17:10:22', 'maria.r@...', 'uploaded 3 files (12.4 MB total)', ''],
            ['2026-04-22 16:12:03', 'maria.r@...', 'completed section "Medical History"', ''],
            ['2026-04-22 15:40:18', 'maria.r@...', 'consented to DCW Terms v2026.04', ''],
            ['2026-04-22 15:38:42', 'system', 'MFA verified · TOTP', ''],
            ['2026-04-22 15:35:10', 'system', 'account created · maria.r@outlook.com', ''],
          ].map(([ts, who, what, type], i) => (
            <div key={i} className="timeline-item" style={{gridTemplateColumns:'180px 140px 1fr'}}>
              <div className="when">{ts}</div>
              <div className="when" style={{paddingTop:4, color: type==='ai'?'var(--info)':type==='warn'?'var(--warn)':'var(--ink-2)'}}>{who}</div>
              <div className={`body ${type}`}>
                <div style={{fontSize:13}}>{what} {type==='ai' && <Badge variant="info"><Icon name="sparkle" size={10}/> AI</Badge>}</div>
              </div>
            </div>
          ))}
        </div>
      </div>
    </div>
  </div>
);

// ─────────── Analytics ───────────
const ReviewerAnalytics = () => (
  <div className="main-col">
    <div className="page-head">
      <div>
        <h1>Analytics</h1>
        <p className="lead">Your team\'s throughput and SLA — last 30 days</p>
      </div>
      <div style={{display:'flex', gap:8}}>
        <div className="seg" style={{padding:2}}>
          <button>7d</button><button className="on">30d</button><button>90d</button>
        </div>
        <Btn variant="secondary" size="sm"><Icon name="download" size={13}/> Export</Btn>
      </div>
    </div>
    <div className="page-body">
      <div className="grid-4" style={{marginBottom:20}}>
        <StatCard label="Cases reviewed" value="147" delta="+12" deltaDir="up" note="vs prev 30d"/>
        <StatCard label="Avg review time" value="2.1d" delta="−14%" deltaDir="up"/>
        <StatCard label="SLA compliance" value="96%" delta="+2pp" deltaDir="up"/>
        <StatCard label="Escalation rate" value="8%" note="target < 10%"/>
      </div>

      <div style={{display:'grid', gridTemplateColumns:'2fr 1fr', gap:18, marginBottom:18}}>
        <div className="card">
          <div style={{padding:'14px 20px', borderBottom:'1px solid var(--line)', display:'flex', justifyContent:'space-between'}}>
            <h3 style={{fontFamily:'var(--serif)', fontSize:18, fontWeight:400}}>Queue depth · rolling 30 days</h3>
            <div className="tiny">Cases waiting</div>
          </div>
          <div style={{padding:'22px 24px', height:240, display:'flex', alignItems:'flex-end', gap:3}}>
            {Array.from({length:30}).map((_,i) => {
              const h = 30 + Math.abs(Math.sin(i * 0.7) * 60) + (i > 20 ? 20 : 0);
              return <div key={i} style={{flex:1, height:`${h}%`, background: i>25?'var(--warn)':'var(--accent)', opacity: i>25?0.85:0.6, borderRadius:'3px 3px 0 0'}}/>;
            })}
          </div>
          <div style={{padding:'0 24px 16px', display:'flex', justifyContent:'space-between', fontSize:11, color:'var(--ink-3)', fontFamily:'var(--mono)'}}>
            <span>Mar 25</span><span>Apr 9</span><span>Apr 23</span>
          </div>
        </div>

        <div className="card">
          <div style={{padding:'14px 20px', borderBottom:'1px solid var(--line)'}}>
            <h3 style={{fontFamily:'var(--serif)', fontSize:18, fontWeight:400}}>Case type mix</h3>
          </div>
          <div style={{padding:'18px 20px'}}>
            {[
              ['SSDI', 58, 'var(--accent)'],
              ['SSI', 22, 'var(--info)'],
              ['VA Disability', 14, 'var(--warn)'],
              ['VA Healthcare', 6, 'var(--ink-3)'],
            ].map(([label, pct, color]) => (
              <div key={label} style={{marginBottom:14}}>
                <div style={{display:'flex', justifyContent:'space-between', fontSize:13, marginBottom:4}}>
                  <span>{label}</span><span className="mono tiny">{pct}%</span>
                </div>
                <div style={{height:8, background:'var(--bg-sunk)', borderRadius:4, overflow:'hidden'}}>
                  <div style={{width:pct+'%', height:'100%', background:color}}/>
                </div>
              </div>
            ))}
          </div>
        </div>
      </div>

      <div className="card">
        <div style={{padding:'14px 20px', borderBottom:'1px solid var(--line)'}}>
          <h3 style={{fontFamily:'var(--serif)', fontSize:18, fontWeight:400}}>Top outstanding SLAs</h3>
        </div>
        <table className="table">
          <thead><tr><th>Case</th><th>Reviewer</th><th>Age</th><th>SLA</th><th>Reason</th><th></th></tr></thead>
          <tbody>
            {[
              ['GE-2026-4758','J.Delacruz','3d','Over','Waiting on docs','danger'],
              ['GE-2026-4751','M.Osei','2d 14h','At risk','Escalated','warn'],
              ['GE-2026-4744','L.Kim','2d 8h','At risk','Onset mismatch','warn'],
            ].map(([c,r,a,s,x,lvl], i) => (
              <tr key={i}>
                <td className="mono" style={{fontSize:12}}>{c}</td>
                <td>{r}</td>
                <td>{a}</td>
                <td><Badge variant={lvl}>{s}</Badge></td>
                <td className="tiny">{x}</td>
                <td><button className="icon-btn"><Icon name="chev" size={14}/></button></td>
              </tr>
            ))}
          </tbody>
        </table>
      </div>
    </div>
  </div>
);

Object.assign(window, { ReviewerLogin, ReviewerSidebar, ReviewerQueue, ReviewerWorkspace, ReviewerDiff, ReviewerDocReview, RequestInfoModal, ApproveModal, EscalateModal, ReviewerAudit, ReviewerAnalytics });
