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

// ─────────── Applicant Dashboard ───────────
const ApplicantDashboard = ({ nav }) => {
  const { tweaks } = useApp();
  const T = tweaks.lang === 'ES';
  return (
    <div style={{flex:1, overflow:'auto'}}>
      <div style={{maxWidth:1080, margin:'0 auto', padding:'32px 36px 80px'}}>
        <div className="rise" style={{display:'flex', justifyContent:'space-between', alignItems:'flex-end', gap:20, flexWrap:'wrap', marginBottom:28}}>
          <div>
            <div className="eyebrow" style={{marginBottom:10}}>{T?'Su expediente':'Your case'}</div>
            <h1 className="h-display" style={{fontSize:44}}>{T?'Hola, María.':'Hi, Maria.'}</h1>
            <p className="lead" style={{marginTop:8, maxWidth:520, fontSize:15}}>{T?'Va muy bien. Su expediente está en revisión. Le avisaremos cuando necesitemos algo de usted.':"You're doing great. Your case is in review. We'll tell you the moment we need anything from you."}</p>
          </div>
          <div style={{display:'flex', gap:10}}>
            <Btn variant="secondary"><Icon name="print" size={14}/> Print summary</Btn>
            <Btn variant="primary" onClick={()=>nav('intake')}><Icon name="play" size={13}/> Continue intake</Btn>
          </div>
        </div>

        {/* Status hero */}
        <div className="card rise-2" style={{padding:'24px 28px', marginBottom:22, background:'linear-gradient(135deg, var(--bg-elev), var(--accent-soft))'}}>
          <div style={{display:'grid', gridTemplateColumns:'1.2fr 1fr', gap:32, alignItems:'center'}}>
            <div>
              <div style={{display:'flex', alignItems:'center', gap:10, marginBottom:8}}>
                <span className="mono tiny" style={{color:'var(--accent-ink)', letterSpacing:'.14em', textTransform:'uppercase'}}>Case GE-2026-4782</span>
                <Badge variant="accent" dot>In review</Badge>
              </div>
              <div style={{fontFamily:'var(--serif)', fontSize:28, lineHeight:1.1}}>Reviewer is checking your medical records.</div>
              <div className="muted" style={{marginTop:8, fontSize:13.5}}>Assigned to <strong style={{color:'var(--ink)'}}>J. Delacruz</strong> · avg turnaround 2 days</div>
              <div style={{display:'flex', gap:10, marginTop:18}}>
                <Btn variant="primary" size="sm" onClick={()=>nav('messages')}><Icon name="chat" size={13}/> Message reviewer</Btn>
                <Btn variant="ghost" size="sm" onClick={()=>nav('audit')}>View case history</Btn>
              </div>
            </div>
            {/* Progress bar of stages */}
            <div>
              <div className="mono tiny" style={{color:'var(--ink-4)', letterSpacing:'.14em', textTransform:'uppercase', marginBottom:10}}>Stages</div>
              <div style={{display:'flex', flexDirection:'column', gap:10}}>
                {[
                  ['Intake', 'done', '100%'],
                  ['Documents', 'partial', '83%'],
                  ['Reviewer check', 'active', '40%'],
                  ['Final review & sign', 'wait', '—'],
                  ['Delivery', 'wait', '—'],
                ].map(([label, state, v], i) => (
                  <div key={i} style={{display:'grid', gridTemplateColumns:'22px 1fr auto', gap:10, alignItems:'center'}}>
                    <div style={{
                      width:18, height:18, borderRadius:'50%',
                      background: state==='done'?'var(--accent)':state==='active'?'var(--bg-elev)':'var(--bg-sunk)',
                      color: state==='done'?'#fff':'var(--ink-3)',
                      border: state==='active'?'2px solid var(--accent)':state==='wait'?'1px solid var(--line-strong)':'0',
                      display:'grid', placeItems:'center'
                    }}>
                      {state === 'done' && <Icon name="check" size={10} stroke={3}/>}
                      {state === 'active' && <div style={{width:6, height:6, borderRadius:'50%', background:'var(--accent)'}}/>}
                    </div>
                    <div style={{fontSize:13, color: state==='wait'?'var(--ink-3)':'var(--ink)'}}>{label}</div>
                    <div className="mono tiny" style={{color:'var(--ink-3)'}}>{v}</div>
                  </div>
                ))}
              </div>
            </div>
          </div>
        </div>

        {/* Three cards */}
        <div className="grid-3 rise-3" style={{marginBottom:22}}>
          <StatCard label="Sections complete" value="12 / 18" delta="67%" deltaDir="up"/>
          <StatCard label="Documents" value="5 / 6" note="1 re-upload needed"/>
          <StatCard label="Next task due" value="Apr 27" note="2 days from now"/>
        </div>

        {/* Outstanding tasks */}
        <div className="card" style={{marginBottom:22}}>
          <div style={{padding:'14px 20px', borderBottom:'1px solid var(--line)', display:'flex', justifyContent:'space-between', alignItems:'center'}}>
            <h3 style={{fontFamily:'var(--serif)', fontSize:20, fontWeight:400}}>Things to finish</h3>
            <span className="mono tiny" style={{color:'var(--ink-3)'}}>3 open</span>
          </div>
          <div>
            {[
              { k:'reup', tag:'Action needed', title:'Re-upload medical records', note:'One image was blurry — see reviewer notes', cta:'Re-upload', icon:'upload', urgent:true, action:()=>nav('docupload') },
              { k:'contra', tag:'Clarify', title:'Which date did your symptoms start?', note:'Two answers don\'t quite match', cta:'Review', icon:'warn', urgent:true, action:()=>nav('contradiction') },
              { k:'work', tag:'To do', title:'Finish your work history section', note:'5 jobs remaining · about 10 minutes', cta:'Continue', icon:'arrow', action:()=>nav('intake') },
            ].map((t, i) => (
              <div key={t.k} style={{padding:'14px 20px', borderBottom: i<2?'1px solid var(--line)':'0', display:'grid', gridTemplateColumns:'28px 1fr auto', gap:14, alignItems:'center'}}>
                <div style={{width:28, height:28, borderRadius:8, background: t.urgent?'var(--warn-soft)':'var(--bg-sunk)', color: t.urgent?'var(--warn)':'var(--ink-3)', display:'grid', placeItems:'center'}}>
                  <Icon name={t.icon} size={14}/>
                </div>
                <div>
                  <div style={{display:'flex', alignItems:'center', gap:8}}>
                    <Badge variant={t.urgent?'warn':null} dot={t.urgent}>{t.tag}</Badge>
                    <span style={{fontSize:14, fontWeight:500}}>{t.title}</span>
                  </div>
                  <div className="tiny" style={{marginTop:2}}>{t.note}</div>
                </div>
                <Btn variant={t.urgent?'accent':'secondary'} size="sm" onClick={t.action}>{t.cta}</Btn>
              </div>
            ))}
          </div>
        </div>

        {/* Bottom grid */}
        <div style={{display:'grid', gridTemplateColumns:'1.3fr 1fr', gap: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:20, fontWeight:400}}>Recent activity</h3>
              <button className="tiny" style={{color:'var(--accent)'}} onClick={()=>nav('audit')}>View full history →</button>
            </div>
            <div style={{padding:'14px 20px'}}>
              <div className="timeline">
                {[
                  { when:'Today · 2:14p', t:'Reviewer requested clarification', body:'One date doesn\'t match another answer — you\'ll find the question in your tasks.', type:'warn' },
                  { when:'Today · 11:02a', t:'Case assigned to J. Delacruz', body:'Experienced SSDI reviewer. Expect a response within 2 business days.', type:'' },
                  { when:'Yesterday · 5:40p', t:'AI extracted 3 dates from MRI report', body:'Auto-filled "first diagnosis" and "last visit" fields. You can edit these.', type:'ai' },
                  { when:'Yesterday · 5:30p', t:'You uploaded Dr_Patel_Visit_2024-11.pdf', body:'Added to medical records folder.', type:'' },
                ].map((e,i) => (
                  <div key={i} className="timeline-item">
                    <div className="when">{e.when}</div>
                    <div className={`body ${e.type}`}>
                      <div style={{fontSize:13.5, fontWeight:500}}>{e.t}</div>
                      <div className="tiny">{e.body}</div>
                    </div>
                  </div>
                ))}
              </div>
            </div>
          </div>

          <div style={{display:'flex', flexDirection:'column', gap:16}}>
            <div className="card card-pad">
              <div style={{display:'flex', gap:12, alignItems:'flex-start'}}>
                <div style={{width:40, height:40, borderRadius:'50%', background:'var(--bg-sunk)', border:'1px solid var(--line)', display:'grid', placeItems:'center', fontSize:12, fontWeight:600, color:'var(--ink-2)'}}>JD</div>
                <div>
                  <div style={{fontSize:14, fontWeight:500}}>J. Delacruz</div>
                  <div className="tiny">Your case reviewer</div>
                </div>
              </div>
              <div className="hr"/>
              <p style={{fontSize:13, color:'var(--ink-2)', lineHeight:1.55, margin:0}}>"Hi Maria — I've started reviewing your medical records. I'll have a preliminary check done by Friday. Please re-upload the one blurry file when you get a chance."</p>
              <Btn variant="secondary" size="sm" block style={{marginTop:12}} onClick={()=>nav('messages')}><Icon name="chat" size={13}/> Open conversation</Btn>
            </div>

            <div className="card card-pad">
              <div className="mono tiny" style={{color:'var(--ink-4)', letterSpacing:'.14em', textTransform:'uppercase', marginBottom:10}}>Data & privacy</div>
              <div className="col" style={{gap:8}}>
                <button className="row" style={{justifyContent:'space-between', padding:'6px 0', fontSize:13, cursor:'pointer'}} onClick={()=>nav('draft')}>
                  <span style={{display:'inline-flex', gap:8, alignItems:'center'}}><Icon name="eye" size={13}/> Preview current draft</span>
                  <Icon name="chev" size={13}/>
                </button>
                <button className="row" style={{justifyContent:'space-between', padding:'6px 0', fontSize:13, cursor:'pointer'}}>
                  <span style={{display:'inline-flex', gap:8, alignItems:'center'}}><Icon name="download" size={13}/> Download my data</span>
                  <Icon name="chev" size={13}/>
                </button>
                <button className="row" style={{justifyContent:'space-between', padding:'6px 0', fontSize:13, cursor:'pointer'}} onClick={()=>nav('retention')}>
                  <span style={{display:'inline-flex', gap:8, alignItems:'center'}}><Icon name="trash" size={13}/> Delete my case</span>
                  <Icon name="chev" size={13}/>
                </button>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  );
};

// ─────────── Messages thread ───────────
const ApplicantMessages = ({ onBack }) => {
  const [draft, setDraft] = useState('');
  const [msgs, setMsgs] = useState([
    { who:'r', name:'J. Delacruz', text:"Hi Maria — I'm J. Delacruz, your reviewer. I've started going through your medical records.", when:'Mon 9:12a', avatar:'JD' },
    { who:'r', name:'J. Delacruz', text:'One of the images came through blurry. Could you re-upload IMG_4218 when you get a moment? No rush — sometime this week is fine.', when:'Mon 9:14a', avatar:'JD', attach:{name:'IMG_4218.heic', note:'Needs re-upload'} },
    { who:'u', text:'Thanks! I\'ll take a new photo tonight. Should I use the scanner at the library instead?', when:'Mon 2:01p' },
    { who:'r', name:'J. Delacruz', text:'Either works! A phone photo on a flat, well-lit surface is usually fine — no need to go out of your way.', when:'Mon 2:08p', avatar:'JD' },
    { who:'sys', text:'You uploaded a new version: Dr_Patel_Visit_2024-11_v2.pdf', when:'Tue 11:40a' },
    { who:'r', name:'J. Delacruz', text:"That's much clearer, thank you. One last thing — I noticed your intake mentions both March 2023 and Summer 2022 for symptom onset. There's a clarification question waiting in your tasks when you have a minute.", when:'Today 2:14p', avatar:'JD' },
  ]);

  const send = () => {
    if (!draft.trim()) return;
    setMsgs(m => [...m, { who:'u', text: draft, when:'Just now' }]);
    setDraft('');
  };

  return (
    <div style={{flex:1, display:'flex', flexDirection:'column', background:'var(--bg)', minHeight:0}}>
      <div style={{padding:'16px 28px', borderBottom:'1px solid var(--line)', display:'flex', alignItems:'center', gap:14, background:'var(--bg-elev)'}}>
        <button className="icon-btn" onClick={onBack}><Icon name="arrowL" size={16}/></button>
        <div style={{width:38, height:38, borderRadius:'50%', background:'var(--accent-soft)', color:'var(--accent-ink)', display:'grid', placeItems:'center', fontWeight:600, fontSize:13}}>JD</div>
        <div style={{flex:1}}>
          <div style={{fontSize:14, fontWeight:500}}>J. Delacruz <span className="mono tiny" style={{color:'var(--ink-3)', marginLeft:4}}>· Reviewer</span></div>
          <div className="tiny" style={{display:'flex', alignItems:'center', gap:6}}><span style={{width:6, height:6, borderRadius:'50%', background:'var(--accent)'}}/> Online now · typically responds in 2 hours</div>
        </div>
        <Badge variant="accent" dot>End-to-end encrypted</Badge>
      </div>

      <div style={{flex:1, overflow:'auto', padding:'26px 32px', display:'flex', flexDirection:'column', gap:14, maxWidth:760, margin:'0 auto', width:'100%'}}>
        {msgs.map((m, i) => {
          if (m.who === 'sys') return (
            <div key={i} className="tiny" style={{textAlign:'center', color:'var(--ink-3)', padding:'6px 0', fontStyle:'italic'}}>· {m.text} · <span className="mono">{m.when}</span></div>
          );
          const mine = m.who === 'u';
          return (
            <div key={i} className="rise" style={{display:'flex', flexDirection: mine?'row-reverse':'row', gap:10, alignItems:'flex-end'}}>
              {!mine && <div style={{width:30, height:30, borderRadius:'50%', background:'var(--accent-soft)', color:'var(--accent-ink)', display:'grid', placeItems:'center', fontSize:11, fontWeight:600, flexShrink:0}}>{m.avatar}</div>}
              <div style={{maxWidth: '70%'}}>
                {!mine && <div className="tiny" style={{marginBottom:4, marginLeft:4}}>{m.name}</div>}
                <div style={{
                  background: mine ? 'var(--ink)' : 'var(--bg-elev)',
                  color: mine ? 'var(--bg)' : 'var(--ink)',
                  padding:'12px 16px',
                  borderRadius: mine ? '16px 16px 4px 16px' : '16px 16px 16px 4px',
                  border: mine?'0':'1px solid var(--line)',
                  fontSize:13.5, lineHeight:1.55,
                  boxShadow: mine?'none':'var(--shadow-sm)'
                }}>
                  {m.text}
                  {m.attach && (
                    <div style={{marginTop:10, padding:'10px 12px', background:'var(--bg-sunk)', border:'1px solid var(--line)', borderRadius:8, display:'flex', gap:10, alignItems:'center'}}>
                      <div style={{width:28, height:34, background:'var(--bg-elev)', border:'1px solid var(--line)', borderRadius:4, display:'grid', placeItems:'center', fontSize:9, color:'var(--ink-3)'}}>HEIC</div>
                      <div style={{flex:1, minWidth:0}}>
                        <div style={{fontSize:12.5, fontWeight:500, color:'var(--ink)'}}>{m.attach.name}</div>
                        <div className="tiny" style={{color:'var(--warn)'}}>{m.attach.note}</div>
                      </div>
                      <Btn variant="accent" size="sm">Fix</Btn>
                    </div>
                  )}
                </div>
                <div className="tiny" style={{marginTop:4, textAlign: mine?'right':'left', color:'var(--ink-4)'}}>{m.when}</div>
              </div>
            </div>
          );
        })}
      </div>

      <div style={{padding:'14px 32px 20px', borderTop:'1px solid var(--line)', background:'var(--bg-elev)'}}>
        <div style={{maxWidth:760, margin:'0 auto', background:'var(--bg)', border:'1px solid var(--line-strong)', borderRadius:12, padding:'6px 8px', display:'flex', alignItems:'center', gap:6}}>
          <button className="icon-btn"><Icon name="upload" size={15}/></button>
          <input
            placeholder="Write a reply…"
            value={draft}
            onChange={e=>setDraft(e.target.value)}
            onKeyDown={e=>{ if (e.key==='Enter') send(); }}
            style={{flex:1, border:0, outline:0, background:'transparent', padding:'10px 8px', fontSize:14}}
          />
          <Btn variant="accent" size="sm" onClick={send}><Icon name="send" size={13}/> Send</Btn>
        </div>
        <div className="tiny" style={{textAlign:'center', marginTop:8, color:'var(--ink-4)'}}>Replies usually come within 2 business hours · urgent questions? Call (800) 555-0199</div>
      </div>
    </div>
  );
};

// ─────────── Case history / audit ───────────
const ApplicantAudit = ({ onBack }) => {
  return (
    <div style={{flex:1, overflow:'auto'}}>
      <div style={{maxWidth: 820, margin:'0 auto', padding:'32px 36px 80px'}}>
        <button className="icon-btn" onClick={onBack} style={{marginBottom:10}}><Icon name="arrowL" size={16}/></button>
        <div className="eyebrow" style={{marginBottom:10}}>Case GE-2026-4782 · Full history</div>
        <h1 className="h-section" style={{fontSize:32, marginBottom:10}}>Everything that\'s happened on your case.</h1>
        <p className="muted" style={{marginBottom:22, fontSize:13.5}}>Every step — yours, your reviewer\'s, and the AI — is logged here. You can download this record anytime.</p>

        <div className="card card-pad">
          <div className="timeline">
            {[
              { when:'Today · 2:14p', t:'J. Delacruz requested clarification', body:'Date mismatch flagged: symptom onset answered as both "March 2023" and "Summer 2022".', type:'warn' },
              { when:'Today · 11:02a', t:'Case assigned to reviewer', body:'J. Delacruz (SSDI specialist, 4 yrs) · avg turnaround 2 days.', type:'' },
              { when:'Tue · 11:40a', t:'You uploaded Dr_Patel_Visit_2024-11_v2.pdf', body:'Replaced IMG_4218.heic (blurry).', type:'' },
              { when:'Tue · 10:22a', t:'AI quality check on uploads', body:'Flagged 1/3 images as low-quality. All 3 files virus-scanned — clean.', type:'ai' },
              { when:'Mon · 5:40p', t:'AI extracted dates from MRI report', body:'Auto-populated "first diagnosis" (Feb 2023) and "last visit" (Nov 2024) fields. Confidence: 94%.', type:'ai' },
              { when:'Mon · 5:30p', t:'You uploaded 3 documents', body:'Dr_Patel_Visit_2024-11.pdf, MRI_Report.jpg, IMG_4218.heic.', type:'' },
              { when:'Mon · 4:12p', t:'You completed "Medical History" section', body:'12 of 18 intake sections complete.', type:'' },
              { when:'Mon · 3:40p', t:'You consented to DCW Terms v2026.04', body:'Recorded with timestamp and IP hash.', type:'' },
              { when:'Mon · 3:38p', t:'MFA verified via Authenticator app', body:'Session started — New York, NY.', type:'' },
              { when:'Mon · 3:35p', t:'Account created', body:'maria.r@outlook.com', type:'' },
            ].map((e,i) => (
              <div key={i} className="timeline-item">
                <div className="when">{e.when}</div>
                <div className={`body ${e.type}`}>
                  <div style={{display:'flex', gap:8, alignItems:'center'}}>
                    <span style={{fontSize:13.5, fontWeight:500}}>{e.t}</span>
                    {e.type === 'ai' && <Badge variant="info"><Icon name="sparkle" size={10}/> AI</Badge>}
                    {e.type === 'warn' && <Badge variant="warn">Action</Badge>}
                  </div>
                  <div className="tiny" style={{marginTop:2}}>{e.body}</div>
                </div>
              </div>
            ))}
          </div>
        </div>

        <div style={{display:'flex', gap:10, marginTop: 18, justifyContent:'flex-end'}}>
          <Btn variant="secondary"><Icon name="download" size={13}/> Download as PDF</Btn>
        </div>
      </div>
    </div>
  );
};

Object.assign(window, { ApplicantDashboard, ApplicantMessages, ApplicantAudit });
