/* global React */
const { useState, useEffect, useRef } = React;

// ─────────── Case Type Selection ───────────
const CaseTypeSelect = ({ onDone }) => {
  const { tweaks } = useApp();
  const T = tweaks.lang === 'ES';
  const [sel, setSel] = useState('ssdi');
  const types = [
    { k:'ssdi', ico:'balance', tag:'SSDI', title:T?'Seguro por Discapacidad':'Social Security Disability Insurance', desc:T?'Para quienes han trabajado y pagado al Seguro Social.':'If you have worked and paid into Social Security.', time:T?'Típicamente 40–55 min':'Typically 40–55 min' },
    { k:'ssi', ico:'shield', tag:'SSI', title:T?'Ingreso de Seguridad Suplementaria':'Supplemental Security Income', desc:T?'Para adultos o niños con ingresos limitados y discapacidad.':'For adults or children with limited income and a disability.', time:T?'Típicamente 45–60 min':'Typically 45–60 min' },
    { k:'vadis', ico:'flag', tag:'VA Disability', title:T?'Discapacidad de VA':'VA Disability Compensation', desc:T?'Para veteranos con condición conectada al servicio.':'For veterans with a service-connected condition.', time:T?'Típicamente 50–70 min':'Typically 50–70 min' },
    { k:'vahealth', ico:'doc', tag:'VA Healthcare', title:T?'Atención de Salud VA':'VA Healthcare Enrollment', desc:T?'Inscripción en el sistema de salud VA.':'Enrollment in the VA healthcare system.', time:T?'Típicamente 25–35 min':'Typically 25–35 min' },
  ];
  return (
    <div className="center-wrap" style={{padding:'44px 24px'}}>
      <div style={{width:'100%', maxWidth:880}} className="rise">
        <div style={{display:'flex', justifyContent:'space-between', alignItems:'flex-end', marginBottom:24, flexWrap:'wrap', gap:16}}>
          <div>
            <div className="eyebrow" style={{marginBottom:14}}>{T?'Tipo de solicitud':'Choose your case type'}</div>
            <h1 className="h-section" style={{fontSize:32, maxWidth:560}}>{T?'¿Qué beneficio está solicitando?':'Which benefit are you applying for?'}</h1>
            <p className="muted" style={{marginTop:8, maxWidth:560, fontSize:14}}>{T?'Puede cambiar esto después. Si no está seguro, use la verificación de elegibilidad.':'You can change this later. Not sure? Take our 2-minute eligibility check.'}</p>
          </div>
          <Stepper steps={18} current={1}/>
        </div>

        <div className="grid-2" style={{gap:14}}>
          {types.map(t => (
            <button key={t.k} className={`option-tile ${sel===t.k?'on':''}`} onClick={()=>setSel(t.k)} style={{padding:'20px 20px'}}>
              <div style={{display:'flex', justifyContent:'space-between', alignItems:'center'}}>
                <div style={{width:36, height:36, borderRadius:8, background: sel===t.k ? 'var(--bg-elev)':'var(--bg-sunk)', color:'var(--accent-ink)', display:'grid', placeItems:'center'}}>
                  <Icon name={t.ico} size={18}/>
                </div>
                <span className="tag">{t.tag}</span>
              </div>
              <div style={{fontFamily:'var(--serif)', fontSize:20, marginTop:4}}>{t.title}</div>
              <div className="tiny" style={{color:'var(--ink-2)', lineHeight:1.5}}>{t.desc}</div>
              <div className="tiny" style={{display:'flex', alignItems:'center', gap:6, marginTop:6}}>
                <Icon name="clock" size={12}/> {t.time}
              </div>
            </button>
          ))}
        </div>

        <div className="flag accent" style={{marginTop: 18}}>
          <div className="ico"><Icon name="sparkle" size={16}/></div>
          <div>
            <strong>{T?'¿No está seguro?':'Not sure which one?'}</strong> {T?'Tómese 2 minutos para una verificación rápida de elegibilidad. No guarda respuestas.':'Take a 2-minute eligibility check before committing. Your answers aren\'t saved.'}
            <button style={{color:'inherit', textDecoration:'underline', marginLeft:8, fontWeight:500}}>{T?'Empezar verificación':'Start eligibility check'} →</button>
          </div>
        </div>

        <div style={{display:'flex', justifyContent:'space-between', marginTop:26}}>
          <Btn variant="ghost"><Icon name="arrowL" size={14}/> {T?'Atrás':'Back'}</Btn>
          <Btn variant="primary" size="lg" onClick={onDone}>{T?'Continuar':'Continue'} <Icon name="arrow" size={15}/></Btn>
        </div>
      </div>
    </div>
  );
};

// ─────────── Pre-flight Eligibility ───────────
const PreFlight = ({ onDone }) => {
  const [step, setStep] = useState(0);
  const [eligible, setEligible] = useState(true);
  const qs = [
    { q: 'Are you a U.S. citizen, permanent resident, or refugee/asylee?', opts:['Yes','No','Not sure'] },
    { q: 'Do you have a medical condition that has lasted (or is expected to last) at least 12 months?', opts:['Yes','No'] },
    { q: 'Are you currently working? If yes, how much are you earning?', opts:['Not working','Less than $1,550/month','$1,550 or more'] },
    { q: 'Have you worked and paid Social Security taxes in at least 5 of the past 10 years?', opts:['Yes','No','Not sure'] },
  ];
  const done = step >= qs.length;
  return (
    <div className="center-wrap" style={{padding:'40px 24px'}}>
      <div style={{width:'100%', maxWidth:620}} className="rise">
        <div style={{display:'flex', justifyContent:'space-between', alignItems:'center', marginBottom:20}}>
          <div className="eyebrow">Quick eligibility check</div>
          <div className="tiny mono" style={{color:'var(--ink-4)'}}>{done ? 'RESULT' : `${step+1} / ${qs.length}`}</div>
        </div>
        <Progress value={done ? 100 : ((step)/qs.length)*100}/>

        {!done ? (
          <div className="card card-pad rise-2" style={{marginTop:22, padding:'26px 28px'}}>
            <div className="mono tiny" style={{color:'var(--ink-4)', letterSpacing:'.14em', textTransform:'uppercase', marginBottom:8}}>Question {step+1}</div>
            <h2 className="h-card" style={{fontSize:22, marginBottom:18}}>{qs[step].q}</h2>
            <div style={{display:'flex', flexDirection:'column', gap:8}}>
              {qs[step].opts.map((o,i) => (
                <button
                  key={i}
                  className="option-tile"
                  style={{padding:'14px 16px'}}
                  onClick={()=>{ setStep(s=>s+1); if (o === 'No' || o === '$1,550 or more') setEligible(false); }}
                >
                  <div style={{display:'flex', alignItems:'center', justifyContent:'space-between'}}>
                    <span style={{fontSize:14.5}}>{o}</span>
                    <Icon name="arrow" size={14}/>
                  </div>
                </button>
              ))}
            </div>
            <Explainer>
              Your answers here are <strong>not saved</strong> and won't affect your application. This is just for guidance.
            </Explainer>
          </div>
        ) : (
          <div className="card card-pad rise-2" style={{marginTop:22, padding:'26px 28px'}}>
            {eligible ? <>
              <div style={{width:44, height:44, borderRadius:12, background:'var(--accent-soft)', color:'var(--accent-ink)', display:'grid', placeItems:'center', marginBottom:12}}>
                <Icon name="check" size={22}/>
              </div>
              <h2 className="h-section" style={{fontSize:26}}>Looks like a strong match</h2>
              <p className="muted" style={{marginTop:8, marginBottom:16, fontSize:14}}>
                Based on your answers, you likely qualify to apply for <strong style={{color:'var(--ink)'}}>SSDI</strong>. A human reviewer will verify everything.
              </p>
              <Explainer>
                <strong>This is not an approval.</strong> The final decision is made by the Social Security Administration. This screening is an estimate only.
              </Explainer>
            </> : <>
              <div style={{width:44, height:44, borderRadius:12, background:'var(--warn-soft)', color:'var(--warn)', display:'grid', placeItems:'center', marginBottom:12}}>
                <Icon name="info" size={22}/>
              </div>
              <h2 className="h-section" style={{fontSize:26}}>You may not meet every requirement</h2>
              <p className="muted" style={{marginTop:8, marginBottom:16, fontSize:14}}>
                Based on what you shared, you may not qualify for this specific benefit — but you might qualify for another. Would you like to try SSI instead?
              </p>
            </>}
            <div style={{display:'flex', gap:10, marginTop:6, justifyContent:'space-between'}}>
              <Btn variant="ghost" onClick={()=>{setStep(0); setEligible(true);}}><Icon name="refresh" size={14}/> Restart check</Btn>
              <Btn variant="primary" onClick={onDone}>Continue to application <Icon name="arrow" size={15}/></Btn>
            </div>
          </div>
        )}
      </div>
    </div>
  );
};

// ─────────── Intake Sections (data) ───────────
const INTAKE_SECTIONS = [
  { k:'personal', title:'About you', steps: ['Name & DOB','Contact','Address','Marital status'] },
  { k:'medical', title:'Medical history', steps: ['Primary condition','Diagnosis date','Treating doctors','Medications','Hospitalizations'] },
  { k:'work', title:'Work history', steps: ['Current work','Past 15 years','Education','Skills'] },
  { k:'daily', title:'Daily living', steps: ['Typical day','Mobility','Self-care','Social'] },
  { k:'financial', title:'Finances', steps: ['Income','Resources','Dependents'] },
];

// ─────────── Smart Intake (hybrid) ───────────
const SmartIntake = ({ onDone, onMessages }) => {
  const { tweaks } = useApp();
  const T = tweaks.lang === 'ES';
  const [messages, setMessages] = useState([
    { who:'g', text: T?'Hola María 👋 Soy su asistente. Trabajemos juntos en su solicitud de SSDI. Todo lo que escriba se guarda automáticamente. ¿Lista para empezar?':"Hi Maria — I'm your guide. Let's work through your SSDI application together. Everything you type is saved as you go. Ready when you are." },
    { who:'u', text: T?'Sí, gracias':"Yes, let's start"},
    { who:'g', text: T?'Perfecto. Empecemos por algo fácil: ¿Cuándo comenzó a afectarle su condición de salud en el trabajo o actividades diarias?':"Great. Let's start with something easy — when did your health condition first start affecting your work or daily activities?" },
    { who:'u', text: T?'Alrededor de marzo de 2023. La fibromialgia se intensificó mucho.':'Around March 2023. My fibromyalgia flared up badly then.' },
    { who:'g', text: T?'Gracias por compartir. Eso nos ayuda mucho. ¿Recuerda haber visto a un médico en ese momento? El nombre y la fecha aproximada es suficiente por ahora.':'Thanks for sharing that. Do you remember seeing a doctor around then? Their name and an approximate date is enough for now.', explainer: T?'¿Por qué preguntamos?': 'Why we\'re asking', explainerBody: T?'La SSA necesita ver un registro médico continuo. Si no recuerda el nombre exacto, está bien — puede añadirlo después.':'The SSA needs to see a continuous medical record. If you don\'t remember the exact name, that\'s OK — you can add it later.' },
  ]);
  const [input, setInput] = useState('');
  const [sectionIdx, setSectionIdx] = useState(1);
  const [stepIdx, setStepIdx] = useState(2);
  const chatRef = useRef(null);

  useEffect(() => {
    chatRef.current?.scrollTo({ top: chatRef.current.scrollHeight, behavior:'smooth' });
  }, [messages]);

  const send = () => {
    if (!input.trim()) return;
    setMessages(m => [...m, { who:'u', text: input }]);
    setInput('');
    setTimeout(() => {
      setMessages(m => [...m, {
        who:'g',
        text: T?'Anotado. ¿Su médico le recetó algún medicamento para la fibromialgia? Si es así, ¿recuerda los nombres?':"Got it. Did your doctor prescribe any medications for your fibromyalgia? If so, do you remember which ones?",
        explainer: T?'Pista útil':'Helpful hint',
        explainerBody: T?'Una foto de la etiqueta del medicamento funciona. La leeremos y la completaremos por usted.':'A photo of the prescription label works — we\'ll read it and fill this in for you.'
      }]);
      setStepIdx(s => Math.min(s+1, 4));
    }, 600);
  };

  const progress = Math.round(((sectionIdx + stepIdx/5) / INTAKE_SECTIONS.length) * 100);

  return (
    <div className="intake" style={tweaks.density === 'compact' ? {gridTemplateColumns:'220px 1fr 300px'} : null}>
      {/* LEFT NAV */}
      <aside className="intake-nav">
        <div style={{display:'flex', justifyContent:'space-between', marginBottom: 18, alignItems:'center'}}>
          <div className="mono tiny" style={{color:'var(--ink-4)', letterSpacing:'.14em', textTransform:'uppercase'}}>Progress</div>
          <div style={{fontSize:13, fontWeight:500}}>{progress}%</div>
        </div>
        <Progress value={progress}/>
        <div style={{marginTop:22}}>
          {INTAKE_SECTIONS.map((sec, i) => (
            <div key={sec.k} className="sec">
              <div className="sec-t" style={{display:'flex', justifyContent:'space-between'}}>
                <span>{sec.title}</span>
                {i < sectionIdx && <Icon name="check" size={12}/>}
              </div>
              {sec.steps.map((st, j) => {
                const isDone = i < sectionIdx || (i === sectionIdx && j < stepIdx);
                const isOn = i === sectionIdx && j === stepIdx;
                return (
                  <div key={j} className={`step ${isDone?'done':''} ${isOn?'on':''}`}>
                    <div className="tick">{isDone && <Icon name="check" size={9} stroke={2.4}/>}</div>
                    <span>{st}</span>
                  </div>
                );
              })}
            </div>
          ))}
        </div>
      </aside>

      {/* CHAT */}
      <div style={{position:'relative', display:'flex', flexDirection:'column', minHeight:0}}>
        <div style={{padding:'16px 40px 8px', display:'flex', justifyContent:'space-between', alignItems:'center', borderBottom:'1px solid var(--line)', background:'var(--bg)'}}>
          <div>
            <div className="mono tiny" style={{color:'var(--ink-4)', letterSpacing:'.14em', textTransform:'uppercase'}}>{INTAKE_SECTIONS[sectionIdx].title}</div>
            <div style={{fontFamily:'var(--serif)', fontSize:20}}>{INTAKE_SECTIONS[sectionIdx].steps[stepIdx]}</div>
          </div>
          <div style={{display:'flex', gap:8, alignItems:'center'}}>
            <Btn variant="ghost" size="sm"><Icon name="download" size={13}/> Save & exit</Btn>
            <Btn variant="ghost" size="sm" onClick={onMessages}><Icon name="chat" size={13}/> Messages <Badge variant="accent">2</Badge></Btn>
          </div>
        </div>

        <div className="intake-chat" ref={chatRef} style={tweaks.density === 'compact' ? {padding:'24px 28px 120px'} : null}>
          {messages.map((m,i) => (
            m.who === 'g'
              ? <div key={i} className="bubble-g rise">
                  <div className="who">Guide</div>
                  <div>{m.text}</div>
                  {m.explainer && (
                    <div className="explainer" style={{marginTop:10}}>
                      <Icon name="info" size={15}/>
                      <div><strong>{m.explainer}: </strong>{m.explainerBody}</div>
                    </div>
                  )}
                </div>
              : <div key={i} className="bubble-u rise">{m.text}</div>
          ))}
        </div>

        <div className="composer">
          <div className="composer-inner">
            <button className="icon-btn" title="Attach"><Icon name="upload" size={15}/></button>
            <input
              placeholder={T?'Escriba su respuesta…':'Type your answer…'}
              value={input}
              onChange={e=>setInput(e.target.value)}
              onKeyDown={e=>{ if (e.key === 'Enter') send(); }}
            />
            <button className="icon-btn" title="Voice"><Icon name="phone" size={15}/></button>
            <Btn variant="accent" size="sm" onClick={send}><Icon name="send" size={13}/></Btn>
          </div>
        </div>
      </div>

      {/* RIGHT — live answer panel */}
      <aside className="intake-side">
        <div style={{display:'flex', justifyContent:'space-between', alignItems:'center', marginBottom: 16}}>
          <div className="mono tiny" style={{color:'var(--ink-4)', letterSpacing:'.14em', textTransform:'uppercase'}}>Your answers</div>
          <button className="tiny" style={{color:'var(--accent)'}}>Review all</button>
        </div>
        <div className="col" style={{gap:10}}>
          {[
            ['Full name', 'Maria L. Ramirez'],
            ['Date of birth', 'Jun 12, 1979 (46)'],
            ['Email', 'maria.r@outlook.com'],
            ['Primary condition', 'Fibromyalgia'],
            ['Condition onset', 'March 2023'],
          ].map(([k,v]) => (
            <div key={k} style={{display:'flex', justifyContent:'space-between', fontSize:13, padding:'8px 0', borderBottom:'1px solid var(--line)'}}>
              <span className="muted" style={{fontSize:12.5}}>{k}</span>
              <span style={{fontWeight:500, textAlign:'right', maxWidth:180}}>{v}</span>
            </div>
          ))}
        </div>

        <div style={{marginTop:22}}>
          <div className="mono tiny" style={{color:'var(--ink-4)', letterSpacing:'.14em', textTransform:'uppercase', marginBottom:10}}>Session</div>
          <div className="flag accent" style={{fontSize:12.5}}>
            <div className="ico"><Icon name="shield" size={14}/></div>
            <div><strong>Auto-saved</strong> · 2s ago. You can close this tab and come back anytime.</div>
          </div>
        </div>

        <div style={{marginTop:16}}>
          <Btn variant="secondary" block size="sm" onClick={onDone}><Icon name="doc" size={13}/> Preview draft so far</Btn>
        </div>
      </aside>

      <SaveBar label={T?'Progreso guardado · retome en cualquier dispositivo':'Progress saved · resumes on any device'}/>
    </div>
  );
};

// ─────────── Contradiction Resolution ───────────
const ContradictionScreen = ({ onDone, onBack }) => {
  const [choice, setChoice] = useState(null);
  return (
    <div className="center-wrap" style={{padding:'40px 24px'}}>
      <div style={{width:'100%', maxWidth: 640}} className="rise">
        <div className="flag warn" style={{marginBottom:20}}>
          <div className="ico"><Icon name="warn" size={16}/></div>
          <div><strong>One quick thing.</strong> We found two answers that don't quite match. Help us pick the right one — this won't delay your case.</div>
        </div>

        <h2 className="h-section" style={{fontSize:26, marginBottom:6}}>Which date is correct?</h2>
        <p className="muted" style={{fontSize:13.5, marginBottom:22}}>You mentioned your condition started at two different times. Pick the one that feels closest to the truth — approximate is fine.</p>

        <div className="col" style={{gap:12}}>
          {[
            { k:'a', label:'March 2023', where:'You said: "Around March 2023. The fibromyalgia flared up badly then."', section:'Medical history · Step 1', when:'14 minutes ago' },
            { k:'b', label:'Summer 2022', where:'In your intake, you answered "Summer 2022" to the question "When did symptoms first appear?"', section:'Medical history · Step 2', when:'9 minutes ago' },
          ].map(opt => (
            <button key={opt.k} className={`option-tile ${choice===opt.k?'on':''}`} onClick={()=>setChoice(opt.k)}>
              <div style={{display:'flex', justifyContent:'space-between', alignItems:'flex-start', gap:12}}>
                <div>
                  <div className="tag" style={{marginBottom:6}}>{opt.section} · {opt.when}</div>
                  <div style={{fontFamily:'var(--serif)', fontSize:22, marginBottom:6}}>{opt.label}</div>
                  <div className="tiny" style={{color:'var(--ink-2)', fontStyle:'italic'}}>“{opt.where}”</div>
                </div>
                <div style={{width:20, height:20, borderRadius:'50%', border:'2px solid var(--line-strong)', background: choice===opt.k ? 'var(--accent)':'transparent', borderColor: choice===opt.k ? 'var(--accent)':'var(--line-strong)', display:'grid', placeItems:'center'}}>
                  {choice === opt.k && <Icon name="check" size={12} stroke={3}/>}
                </div>
              </div>
            </button>
          ))}
          <button className={`option-tile ${choice==='c'?'on':''}`} style={{padding:'14px 18px'}} onClick={()=>setChoice('c')}>
            <div style={{display:'flex', alignItems:'center', justifyContent:'space-between'}}>
              <span style={{fontSize:14}}>Neither — let me write a different date</span>
              <Icon name="pen" size={14}/>
            </div>
          </button>
        </div>

        <Explainer>
          We check for small mismatches because the SSA rejects applications with conflicting dates. It's usually a small memory thing — not a problem.
        </Explainer>

        <div style={{display:'flex', justifyContent:'space-between', marginTop:26}}>
          <Btn variant="ghost" onClick={onBack}><Icon name="arrowL" size={14}/> Back</Btn>
          <Btn variant="primary" onClick={onDone} disabled={!choice} style={!choice?{opacity:.5, pointerEvents:'none'}:null}>Save answer <Icon name="arrow" size={15}/></Btn>
        </div>
      </div>
    </div>
  );
};

Object.assign(window, { CaseTypeSelect, PreFlight, SmartIntake, ContradictionScreen, INTAKE_SECTIONS });
