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

// ─────────── Landing ───────────
const ApplicantLanding = ({ onStart }) => {
  const { tweaks } = useApp();
  const T = tweaks.lang === 'ES';
  return (
    <div className="center-wrap home-wrap" style={{padding:'48px 24px 72px', position:'relative', overflow:'hidden'}}>
      <div className="home-orb orb-a"/>
      <div className="home-orb orb-b"/>
      <div className="home-grid" style={{width:'100%', maxWidth:1180, display:'grid', gridTemplateColumns:'1.25fr .9fr', gap:28, alignItems:'stretch', position:'relative', zIndex:1}}>
        <div className="home-hero rise">
          <div className="eyebrow home-kicker" style={{marginBottom:18}}>
            {T ? 'Orquestación digital para expedientes de discapacidad' : 'Digital case orchestration for disability claims'}
          </div>
          <div style={{display:'flex', gap:8, flexWrap:'wrap', marginBottom:20}}>
            <Badge variant="info">SSDI</Badge>
            <Badge variant="info">SSI</Badge>
            <Badge variant="info">VA Disability</Badge>
            <Badge variant="info">VA Healthcare</Badge>
          </div>
          <h1 className="h-display" style={{fontSize:'clamp(48px, 8vw, 86px)', lineHeight:.92, maxWidth:760, margin:0}}>
            {T ? <>Un portal <em>claro</em> para casos complejos.</> : <>A clearer <em>future</em> for complex claims.</>}
          </h1>
          <p className="lead" style={{marginTop:20, maxWidth:620, fontSize:16}}>
            {T
              ? 'GovEase combina orientación conversacional, revisión humana y un flujo seguro de documentos para que cada solicitud avance con menos fricción y más confianza.'
              : 'GovEase combines conversational guidance, human review, and secure document flow so every application moves with less friction and more confidence.'}
          </p>

          <div style={{display:'flex', gap:12, marginTop:28, flexWrap:'wrap'}}>
            <Btn variant="primary" size="lg" onClick={()=>onStart('signup')}>
              {T ? 'Crear expediente' : 'Create your case'} <Icon name="arrow" size={15}/>
            </Btn>
            <Btn variant="secondary" size="lg" onClick={()=>onStart('signin')}>
              {T ? 'Ingresar a un caso existente' : 'Resume an existing case'}
            </Btn>
          </div>

          <div className="home-metrics" style={{display:'grid', gridTemplateColumns:'repeat(3, minmax(0, 1fr))', gap:12, marginTop:34}}>
            {[
              [T ? 'Flujo bilingüe' : 'Bilingual flow', 'EN / ES'],
              [T ? 'Revisión humana' : 'Human review', '100%'],
              [T ? 'Guardado continuo' : 'Continuous save', '< 2s'],
            ].map(([label, value]) => (
              <div key={label} className="home-chip">
                <div className="mono tiny" style={{color:'var(--ink-4)', letterSpacing:'.12em', textTransform:'uppercase'}}>{label}</div>
                <div style={{fontFamily:'var(--serif)', fontSize:30, marginTop:6}}>{value}</div>
              </div>
            ))}
          </div>
        </div>

        <div style={{display:'grid', gap:16}}>
          <div className="home-panel rise-2">
            <div className="mono tiny" style={{textTransform:'uppercase', letterSpacing:'.14em', color:'var(--accent-ink)'}}>
              {T ? 'Centro de misión' : 'Mission control'}
            </div>
            <div style={{fontFamily:'var(--serif)', fontSize:28, marginTop:10}}>
              {T ? 'Un mismo sistema para solicitantes, reviewers y admins.' : 'One system for applicants, reviewers, and admins.'}
            </div>
            <div className="col" style={{gap:10, marginTop:18}}>
              {[
                [T ? 'Ingreso guiado por conversación' : 'Conversation-led intake', T ? 'Preguntas adaptativas con guardado continuo.' : 'Adaptive questions with save-and-resume built in.'],
                [T ? 'Documentos con validación' : 'Document intelligence', T ? 'Checklist dinámico, carga segura y reenvío guiado.' : 'Dynamic checklist, secure uploads, and guided re-uploads.'],
                [T ? 'Supervisión verificable' : 'Verifiable oversight', T ? 'Timeline de auditoría, decisiones humanas y trazabilidad.' : 'Audit timeline, human approvals, and full traceability.'],
              ].map(([title, body]) => (
                <div key={title} className="home-line">
                  <div style={{fontSize:14.5, fontWeight:600}}>{title}</div>
                  <div className="tiny" style={{marginTop:4}}>{body}</div>
                </div>
              ))}
            </div>
          </div>

          <div className="home-stack rise-3">
            {[
              [T ? 'Applicant' : 'Applicant', T ? 'Inicio, autenticación, intake, dashboard, firma final.' : 'Welcome, auth, intake, dashboard, final acknowledgment.'],
              [T ? 'Reviewer' : 'Reviewer', T ? 'Queue, workspace, diff, revisión documental, escalación.' : 'Queue, workspace, diff view, document review, escalation.'],
              [T ? 'Admin' : 'Admin', T ? 'Monitoreo, roles, auditoría, IA, retención.' : 'Monitoring, roles, audit, AI activity, retention.'],
            ].map(([title, body]) => (
              <div key={title} className="home-stack-card">
                <div style={{display:'flex', justifyContent:'space-between', alignItems:'center'}}>
                  <span style={{fontSize:15, fontWeight:600}}>{title}</span>
                  <span className="home-dot"/>
                </div>
                <div className="tiny" style={{marginTop:8}}>{body}</div>
              </div>
            ))}
          </div>
        </div>
      </div>
    </div>
  );
};

// ─────────── Sign In / Sign Up ───────────
const ApplicantAuth = ({ mode = 'signin', onDone, onSwitch, onForgot }) => {
  const { tweaks } = useApp();
  const T = tweaks.lang === 'ES';
  const [show, setShow] = useState(false);
  const isSignup = mode === 'signup';
  return (
    <div className="center-wrap">
      <div className="center-card rise">
        <div className="eyebrow" style={{marginBottom:16}}>{isSignup ? (T?'Nueva cuenta':'Create account') : (T?'Ingresar':'Sign in')}</div>
        <h2 className="h-section">{isSignup ? (T?'Empiece su expediente.':'Start your case.') : (T?'Bienvenido de nuevo.':'Welcome back.')}</h2>
        <p className="muted" style={{marginTop:8, marginBottom:22, fontSize:13.5}}>
          {isSignup
            ? (T?'Todo lo que ingrese se guarda de forma segura. Puede pausar cuando quiera.' : 'Everything you enter is saved securely. You can pause anytime.')
            : (T?'Ingrese a su expediente en curso.' : 'Pick up where you left off.')}
        </p>

        <div style={{display:'flex', flexDirection:'column', gap:14}}>
          {isSignup && (
            <div className="grid-2">
              <Field label={T?'Nombre':'First name'}>
                <input className="input" placeholder={T?'María':'Maria'}/>
              </Field>
              <Field label={T?'Apellido':'Last name'}>
                <input className="input" placeholder={T?'Ramírez':'Ramirez'}/>
              </Field>
            </div>
          )}
          <Field label={T?'Correo electrónico':'Email'}>
            <input className="input" placeholder="you@email.com" defaultValue={!isSignup?'maria.r@outlook.com':''}/>
          </Field>
          <Field label={T?'Contraseña':'Password'} hint={isSignup ? (T?'Mínimo 12 caracteres, una mayúscula, un número.' : 'At least 12 characters, 1 uppercase, 1 number.') : null}>
            <div style={{position:'relative'}}>
              <input className="input" type={show?'text':'password'} style={{paddingRight:40}} defaultValue={isSignup?'':'••••••••••••'}/>
              <button className="icon-btn" onClick={()=>setShow(!show)} style={{position:'absolute', right:4, top:4}}>
                <Icon name={show?'eyeOff':'eye'} size={15}/>
              </button>
            </div>
          </Field>

          {isSignup && (
            <label className="check">
              <input type="checkbox"/>
              <span>{T?'Tengo 18 años o más y acepto el ':'I am 18+ and agree to the '}<a style={{color:'var(--accent)', textDecoration:'underline'}}>{T?'Aviso de Privacidad':'Privacy Notice'}</a>.</span>
            </label>
          )}

          {!isSignup && (
            <div style={{display:'flex', justifyContent:'space-between', alignItems:'center'}} onClick={(e)=>{ if (e.target.tagName === 'A') onForgot?.(); }}>
              <label className="check"><input type="checkbox"/> <span>{T?'Recordarme':'Remember me'}</span></label>
              <a className="tiny" style={{color:'var(--accent)'}}>{T?'¿Olvidó su contraseña?':'Forgot password?'}</a>
            </div>
          )}

          <Btn variant="primary" size="lg" block onClick={onDone}>
            {isSignup ? (T?'Crear cuenta':'Create account') : (T?'Ingresar':'Sign in')}
            <Icon name="arrow" size={15}/>
          </Btn>

          <div className="divider-x">{T?'O':'Or'}</div>

          <div className="col" style={{gap:8}}>
            <Btn variant="secondary" block><Icon name="shield" size={15}/> {T?'Continuar con ID.me':'Continue with ID.me'}</Btn>
            <Btn variant="secondary" block><Icon name="shieldCheck" size={15}/> {T?'Continuar con Login.gov':'Continue with Login.gov'}</Btn>
          </div>

          <p className="tiny" style={{textAlign:'center', marginTop:6}}>
            {isSignup
              ? <>{T?'¿Ya tiene cuenta? ':'Already have an account? '}<a style={{color:'var(--accent)', cursor:'pointer'}} onClick={()=>onSwitch('signin')}>{T?'Ingresar':'Sign in'}</a></>
              : <>{T?'¿Nuevo aquí? ':'New here? '}<a style={{color:'var(--accent)', cursor:'pointer'}} onClick={()=>onSwitch('signup')}>{T?'Cree una cuenta':'Create an account'}</a></>
            }
          </p>
        </div>
      </div>
    </div>
  );
};

// ─────────── MFA ───────────
const ApplicantMFA = ({ onDone }) => {
  const { tweaks } = useApp();
  const T = tweaks.lang === 'ES';
  const [code, setCode] = useState(['','','','','','']);
  const [method, setMethod] = useState('app');
  const onKey = (i, v) => {
    if (!/^[0-9]?$/.test(v)) return;
    const next = [...code]; next[i] = v; setCode(next);
    if (v && i < 5) document.getElementById('mfa-'+(i+1))?.focus();
  };
  const filled = code.every(c=>c);
  return (
    <div className="center-wrap">
      <div className="center-card rise" style={{maxWidth: 460}}>
        <div style={{width:44, height:44, borderRadius:12, background:'var(--accent-soft)', color:'var(--accent-ink)', display:'grid', placeItems:'center', marginBottom:14}}>
          <Icon name="shield" size={22}/>
        </div>
        <h2 className="h-section">{T?'Verifique que es usted':'Verify it\'s you'}</h2>
        <p className="muted" style={{marginTop:8, marginBottom:20, fontSize:13.5}}>
          {T?'Ingrese el código de 6 dígitos desde ':'Enter the 6-digit code from '}
          {method==='app' ? (T?'su app de autenticación':'your authenticator app') : T?'tu SMS a •••• 3129':'your SMS to •••• 3129'}.
        </p>

        <div style={{display:'flex', gap:8, marginBottom: 18}}>
          {code.map((c, i) => (
            <input
              key={i}
              id={'mfa-'+i}
              value={c}
              onChange={e=>onKey(i, e.target.value)}
              className="input"
              style={{textAlign:'center', fontFamily:'var(--mono)', fontSize:22, padding:'14px 0', letterSpacing:'.02em'}}
              maxLength={1}
              inputMode="numeric"
            />
          ))}
        </div>

        <Btn variant="primary" size="lg" block onClick={onDone} disabled={!filled} style={!filled?{opacity:.5, pointerEvents:'none'}:null}>
          {T?'Verificar':'Verify'} <Icon name="arrow" size={15}/>
        </Btn>

        <div className="divider-x"/>

        <div style={{display:'flex', flexDirection:'column', gap:8}}>
          <button className="flag" style={{background: method==='app'?'var(--accent-soft)':'var(--bg-sunk)', borderColor: method==='app'?'transparent':'var(--line)', textAlign:'left', cursor:'pointer'}} onClick={()=>setMethod('app')}>
            <div className="ico" style={{color: method==='app'?'var(--accent-ink)':'var(--ink-3)'}}><Icon name="cpu" size={16}/></div>
            <div>
              <div style={{fontWeight:500}}>{T?'App de autenticación':'Authenticator app'}</div>
              <div className="tiny">Google Authenticator, 1Password, Authy</div>
            </div>
          </button>
          <button className="flag" style={{background: method==='sms'?'var(--accent-soft)':'var(--bg-sunk)', borderColor: method==='sms'?'transparent':'var(--line)', textAlign:'left', cursor:'pointer'}} onClick={()=>setMethod('sms')}>
            <div className="ico" style={{color: method==='sms'?'var(--accent-ink)':'var(--ink-3)'}}><Icon name="phone" size={16}/></div>
            <div>
              <div style={{fontWeight:500}}>{T?'SMS a •••• 3129':'Text to •••• 3129'}</div>
              <div className="tiny">{T?'Menos seguro que la app':'Less secure than app'}</div>
            </div>
          </button>
        </div>

        <p className="tiny" style={{textAlign:'center', marginTop:18}}>
          {T?'¿Problemas? ':'Having trouble? '}<a style={{color:'var(--accent)'}}>{T?'Usar código de respaldo':'Use a backup code'}</a>
        </p>
      </div>
    </div>
  );
};

// ─────────── Consent ───────────
const ApplicantConsent = ({ onDone }) => {
  const { tweaks } = useApp();
  const T = tweaks.lang === 'ES';
  const [checks, setChecks] = useState({a:false,b:false,c:false});
  const ready = checks.a && checks.b && checks.c;
  return (
    <div className="center-wrap" style={{padding:'40px 24px'}}>
      <div style={{width:'100%', maxWidth:720}} className="rise">
        <div style={{display:'flex', justifyContent:'space-between', alignItems:'center', marginBottom:22}}>
          <div className="eyebrow">{T?'Consentimiento informado':'Informed consent'}</div>
          <div className="mono tiny" style={{color:'var(--ink-4)', letterSpacing:'.08em'}}>v 2026.04 · REV 12</div>
        </div>
        <h1 className="h-section" style={{marginBottom:14, fontSize:32}}>
          {T ? 'Antes de comenzar, lea y acepte.' : 'Before we begin, please read and agree.'}
        </h1>
        <p className="lead" style={{marginBottom:22}}>
          {T ? 'Queremos que entienda qué hacemos con su información. Puede retirar su consentimiento en cualquier momento.' : 'We want you to understand how we use your information. You can withdraw consent anytime.'}
        </p>

        <div className="card card-pad" style={{padding:0}}>
          {[
            { k:'a', title:T?'Uso de su información':'How we use your information', body:T?'Su información se usa únicamente para preparar esta solicitud. No se vende, no se comparte con terceros para marketing, y no se envía a ninguna agencia sin su aprobación.':'Your information is used only to prepare this application. It is never sold, shared for marketing, or submitted to any agency without your approval.'},
            { k:'b', title:T?'Asistencia con IA + revisión humana':'AI assistance + human review', body:T?'Usamos IA para ayudarle a redactar su solicitud. Cada paso es registrado. Un revisor humano verifica todo antes del envío.':'We use AI to help draft your application. Every step is logged. A human reviewer checks everything before anything is submitted.'},
            { k:'c', title:T?'Retención y eliminación':'Retention & deletion', body:T?'Su expediente se retiene por 24 meses después del envío. Puede solicitar eliminación en cualquier momento desde su panel.':'Your case is retained for 24 months after submission. You can request deletion anytime from your dashboard.'},
          ].map(item => (
            <label key={item.k} className="check" style={{padding:'16px 20px', borderBottom:'1px solid var(--line)', cursor:'pointer'}}>
              <input type="checkbox" checked={checks[item.k]} onChange={e=>setChecks(s=>({...s,[item.k]:e.target.checked}))}/>
              <div>
                <div style={{fontSize:14.5, fontWeight:500, color:'var(--ink)', marginBottom:3}}>{item.title}</div>
                <div className="hint">{item.body}</div>
              </div>
            </label>
          ))}
        </div>

        <div className="flag info" style={{marginTop:18}}>
          <div className="ico"><Icon name="info" size={16}/></div>
          <div>
            <strong>{T?'Versión con fecha':'Timestamped'}:</strong> {T?'Su consentimiento se registra con fecha y versión. Copia disponible en su panel.':'Your consent is recorded with a timestamp and version number. A copy is always available in your dashboard.'}
          </div>
        </div>

        <div style={{display:'flex', gap:10, marginTop:24, justifyContent:'space-between', alignItems:'center'}}>
          <Btn variant="ghost">{T?'Imprimir / Descargar PDF':'Print / Save as PDF'}</Btn>
          <div style={{display:'flex', gap:10}}>
            <Btn variant="secondary">{T?'Cancelar':'Not now'}</Btn>
            <Btn variant="accent" size="lg" disabled={!ready} onClick={ready?onDone:null} style={!ready?{opacity:.5, pointerEvents:'none'}:null}>
              {T?'Acepto y continuar':'I agree — continue'} <Icon name="arrow" size={15}/>
            </Btn>
          </div>
        </div>
      </div>
    </div>
  );
};

// ─────────── Forgot Password ───────────
const ApplicantForgot = ({ onDone, onBack }) => {
  const [sent, setSent] = useState(false);
  return (
    <div className="center-wrap">
      <div className="center-card rise" style={{maxWidth: 440}}>
        <button className="icon-btn" onClick={onBack} style={{marginBottom: 8}}><Icon name="arrowL" size={16}/></button>
        {!sent ? <>
          <h2 className="h-section">Reset your password</h2>
          <p className="muted" style={{marginTop:8, marginBottom:20, fontSize:13.5}}>
            We'll email you a link to reset. Links expire after 30 minutes.
          </p>
          <Field label="Email">
            <input className="input" placeholder="you@email.com" defaultValue="maria.r@outlook.com"/>
          </Field>
          <Btn variant="primary" size="lg" block style={{marginTop: 14}} onClick={()=>setSent(true)}>
            Send reset link
          </Btn>
        </> : <>
          <div style={{width:44, height:44, borderRadius:12, background:'var(--accent-soft)', color:'var(--accent-ink)', display:'grid', placeItems:'center', marginBottom:14}}>
            <Icon name="mail" size={22}/>
          </div>
          <h2 className="h-section">Check your email</h2>
          <p className="muted" style={{marginTop:8, marginBottom:20, fontSize:13.5}}>
            We sent a reset link to <strong style={{color:'var(--ink)'}}>maria.r@outlook.com</strong>. It expires in 30 minutes.
          </p>
          <Btn variant="primary" size="lg" block onClick={onDone}>Back to sign in</Btn>
          <p className="tiny" style={{textAlign:'center', marginTop:14}}>
            Didn't get it? <a style={{color:'var(--accent)'}}>Resend</a>
          </p>
        </>}
      </div>
    </div>
  );
};

// ─────────── Language Selection ───────────
const LanguageGate = ({ onDone }) => {
  const { setTweaks } = useApp();
  const pick = (lang) => { setTweaks({lang}); onDone(); };
  return (
    <div className="center-wrap">
      <div className="rise" style={{width:'100%', maxWidth: 560, textAlign:'center'}}>
        <div className="brand" style={{justifyContent:'center', marginBottom: 26, fontSize: 20}}>
          <span className="brand-mark" style={{width:30, height:30, fontSize:19}}>Ge</span>
          <span>GovEase</span>
        </div>
        <h1 className="h-display" style={{fontSize: 44}}>Choose your language</h1>
        <p className="muted" style={{marginTop: 12, marginBottom: 32, fontSize:15}}>Elija su idioma preferido. Puede cambiarlo en cualquier momento.</p>
        <div className="grid-2" style={{gap:14}}>
          <button className="option-tile" onClick={()=>pick('EN')} style={{alignItems:'center', gap:6, padding:'30px 20px'}}>
            <div className="mono tiny" style={{color:'var(--ink-4)', letterSpacing:'.14em', textTransform:'uppercase'}}>English</div>
            <div style={{fontFamily:'var(--serif)', fontSize:36}}>Continue</div>
            <div className="tiny">I prefer English</div>
          </button>
          <button className="option-tile" onClick={()=>pick('ES')} style={{alignItems:'center', gap:6, padding:'30px 20px'}}>
            <div className="mono tiny" style={{color:'var(--ink-4)', letterSpacing:'.14em', textTransform:'uppercase'}}>Español</div>
            <div style={{fontFamily:'var(--serif)', fontSize:36}}>Continuar</div>
            <div className="tiny">Prefiero español</div>
          </button>
        </div>
        <p className="tiny" style={{marginTop: 30}}>More languages coming · Más idiomas en camino</p>
      </div>
    </div>
  );
};

Object.assign(window, { ApplicantLanding, ApplicantAuth, ApplicantMFA, ApplicantConsent, ApplicantForgot, LanguageGate });
