/* ============================================================
   FLUJO COLABORADOR — Bienvenida · Datos · Evaluación
   Exporta: ScreenWelcome, ScreenDatos, ScreenEval
   ============================================================ */
const { useState, useEffect, useRef } = React;
const IHF = window.IH;

/* ---------- Marca compacta ---------- */
function Brand({ small }) {
  return (
    <div style={{ display: 'flex', alignItems: 'center', gap: 11 }}>
      <svg width={small ? 22 : 28} height={small ? 22 : 28} viewBox="0 0 28 28">
        <circle cx="14" cy="14" r="12.5" fill="none" stroke="var(--gold)" strokeWidth="1.2" />
        <circle cx="14" cy="14" r="6.5" fill="none" stroke="var(--ink)" strokeWidth="1.2" />
        <circle cx="14" cy="14" r="1.7" fill="var(--gold)" />
      </svg>
      <div style={{ lineHeight: 1.05 }}>
        <div className="serif" style={{ fontSize: small ? 14 : 16, fontWeight: 600, letterSpacing: '0.01em' }}>Ingeniería Humana</div>
        <div className="mono" style={{ fontSize: small ? 8.5 : 9.5, letterSpacing: '0.16em', color: 'var(--ink-3)', textTransform: 'uppercase', marginTop: 2 }}>El Sendero del Alto Rendimiento</div>
      </div>
    </div>
  );
}

/* ============================================================
   1 · BIENVENIDA
   ============================================================ */
function ScreenWelcome({ onStart, onExec }) {
  return (
    <div className="fade-in" style={{ minHeight: '100vh', display: 'flex', flexDirection: 'column' }}>
      <header style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', padding: '26px 48px', borderBottom: '1px solid var(--hair)' }}>
        <Brand />
        <button className="btn btn-ghost" onClick={onExec} style={{ fontSize: 13 }}>Panel ejecutivo →</button>
      </header>

      <div style={{ flex: 1, display: 'grid', gridTemplateColumns: '1.05fr 0.95fr', alignItems: 'center', maxWidth: 1280, margin: '0 auto', padding: '0 48px', width: '100%', gap: 64 }}>
        <div className="fade-up">
          <div className="eyebrow" style={{ marginBottom: 22 }}>Diagnóstico conductual organizacional</div>
          <h1 className="serif" style={{ fontSize: 58, lineHeight: 1.04, fontWeight: 500, margin: '0 0 24px', letterSpacing: '-0.01em' }}>
            No es un test.<br />Es una <em style={{ fontStyle: 'italic', color: 'var(--gold)' }}>radiografía</em> de cómo opera tu gente.
          </h1>
          <p style={{ fontSize: 17, lineHeight: 1.6, color: 'var(--ink-2)', maxWidth: 480, margin: '0 0 18px' }}>
            Todos llevamos dentro seis arquetipos. La evaluación no etiqueta personas: revela <strong style={{ fontWeight: 600, color: 'var(--ink)' }}>qué arquetipo gobierna hoy</strong> las decisiones, los comportamientos y el desempeño de cada colaborador.
          </p>
          <p style={{ fontSize: 14.5, lineHeight: 1.6, color: 'var(--ink-3)', maxWidth: 460, margin: '0 0 36px' }}>
            60 afirmaciones · 6 arquetipos · un mapa conductual claro para la persona y para la organización.
          </p>
          <div style={{ display: 'flex', gap: 14, alignItems: 'center' }}>
            <button className="btn btn-primary" onClick={onStart} style={{ fontSize: 15, padding: '15px 30px' }}>Comenzar evaluación</button>
            <span className="mono" style={{ fontSize: 12, color: 'var(--ink-3)' }}>≈ 8 minutos</span>
          </div>
        </div>

        <SenderoVisual />
      </div>

      <footer style={{ padding: '20px 48px', borderTop: '1px solid var(--hair)', display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
        <span className="mono" style={{ fontSize: 11, color: 'var(--ink-3)', letterSpacing: '0.06em' }}>PSICOLOGÍA APLICADA · NEUROCIENCIA · ALTO RENDIMIENTO</span>
        <span className="mono" style={{ fontSize: 11, color: 'var(--ink-3)' }}>Grupo Nexa · Confidencial</span>
      </footer>
    </div>
  );
}

/* El sendero de los 6 arquetipos */
function SenderoVisual() {
  return (
    <div className="fade-up" style={{ background: 'var(--panel)', border: '1px solid var(--hair)', borderRadius: 'var(--r-lg)', padding: '38px 34px', boxShadow: 'var(--shadow)' }}>
      <div className="eyebrow" style={{ marginBottom: 26 }}>El sendero · de la contracción a la maestría</div>
      <div style={{ display: 'flex', flexDirection: 'column', gap: 2 }}>
        {IHF.archetypes.map((a, i) => (
          <div key={a.id} style={{ display: 'flex', alignItems: 'center', gap: 16, padding: '13px 0', borderBottom: i < 5 ? '1px solid var(--hair)' : 'none' }}>
            <div style={{ width: 44, height: 44, borderRadius: 10, background: a.hex + '18', display: 'flex', alignItems: 'center', justifyContent: 'center', flex: 'none' }}>
              <Glyph id={a.id} size={24} stroke={1.8} />
            </div>
            <div style={{ flex: 1 }}>
              <div style={{ display: 'flex', alignItems: 'baseline', gap: 10 }}>
                <span className="serif" style={{ fontSize: 18, fontWeight: 600 }}>{a.name}</span>
                <span className="mono" style={{ fontSize: 10, color: 'var(--ink-3)' }}>0{a.order}</span>
              </div>
              <div style={{ fontSize: 12.5, color: 'var(--ink-3)' }}>{a.glyph}</div>
            </div>
            <span className="mono" style={{ fontSize: 9.5, letterSpacing: '0.1em', textTransform: 'uppercase', color: a.hex, fontWeight: 600 }}>
              {a.group === 'riesgo' ? 'Riesgo' : a.group === 'transicion' ? 'Transición' : 'Evolución'}
            </span>
          </div>
        ))}
      </div>
    </div>
  );
}

/* ============================================================
   2 · DATOS GENERALES
   ============================================================ */
function ScreenDatos({ profile, onChange, onNext, onBack }) {
  const fields = [
    { k: 'nombre', label: 'Nombre completo', type: 'text', ph: 'Ej. Ana García' },
    { k: 'empresa', label: 'Empresa', type: 'text', ph: 'Ej. Grupo Nexa' },
    { k: 'area', label: 'Área', type: 'select', opts: IHF.areas },
    { k: 'puesto', label: 'Puesto', type: 'text', ph: 'Ej. Coordinador comercial' },
    { k: 'antiguedad', label: 'Antigüedad', type: 'select', opts: IHF.antiguedades },
    { k: 'sucursal', label: 'Sucursal', type: 'select', opts: IHF.sucursales },
  ];
  const complete = profile.nombre && profile.empresa && profile.area;
  return (
    <FlowShell step="Datos generales" onBack={onBack}>
      <div className="fade-up" style={{ maxWidth: 620, margin: '0 auto', width: '100%' }}>
        <div className="eyebrow" style={{ marginBottom: 14 }}>Antes de comenzar</div>
        <h2 className="serif" style={{ fontSize: 36, fontWeight: 500, margin: '0 0 12px', letterSpacing: '-0.01em' }}>Cuéntanos quién eres</h2>
        <p style={{ fontSize: 15, color: 'var(--ink-2)', margin: '0 0 36px', lineHeight: 1.55 }}>
          Estos datos permiten agrupar tus resultados por área y organización. Tus respuestas son confidenciales.
        </p>
        <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: '22px 24px' }}>
          {fields.map(f => (
            <div key={f.k} style={{ gridColumn: f.k === 'nombre' ? '1 / -1' : 'auto' }}>
              <label className="eyebrow" style={{ display: 'block', marginBottom: 8, fontSize: 10.5 }}>{f.label}</label>
              {f.type === 'select' ? (
                <select value={profile[f.k] || ''} onChange={e => onChange(f.k, e.target.value)} className="ih-input">
                  <option value="" disabled>Selecciona…</option>
                  {f.opts.map(o => <option key={o} value={o}>{o}</option>)}
                </select>
              ) : (
                <input type="text" value={profile[f.k] || ''} placeholder={f.ph}
                  onChange={e => onChange(f.k, e.target.value)} className="ih-input" />
              )}
            </div>
          ))}
        </div>
        <div style={{ display: 'flex', justifyContent: 'flex-end', marginTop: 40 }}>
          <button className="btn btn-primary" disabled={!complete} onClick={onNext} style={{ fontSize: 15, padding: '14px 30px' }}>
            Iniciar evaluación →
          </button>
        </div>
      </div>
      <style>{`
        .ih-input { width:100%; font-family:var(--sans); font-size:15px; color:var(--ink);
          background:var(--panel); border:1px solid var(--hair-2); border-radius:var(--r);
          padding:13px 15px; outline:none; transition:border-color .15s, box-shadow .15s; }
        .ih-input:focus { border-color:var(--gold); box-shadow:0 0 0 3px var(--gold-wash); }
        select.ih-input { appearance:none; cursor:pointer;
          background-image:url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='12' height='12' fill='none' stroke='%238a857b' stroke-width='1.6'%3E%3Cpath d='M2 4l4 4 4-4'/%3E%3C/svg%3E");
          background-repeat:no-repeat; background-position:right 14px center; padding-right:38px; }
      `}</style>
    </FlowShell>
  );
}

/* ============================================================
   3 · EVALUACIÓN  (6 bloques × 10 afirmaciones)
   ============================================================ */
function ScreenEval({ answers, onAnswer, onFinish, onBack, blockIdx, setBlockIdx }) {
  const ids = IHF.order;
  const id = ids[blockIdx];
  const arch = IHF.byId[id];
  const qs = IHF.questions[id];
  const blockAnswers = answers[id] || [];
  const blockDone = blockAnswers.filter(Boolean).length;

  const totalAnswered = ids.reduce((s, a) => s + (answers[a] || []).filter(Boolean).length, 0);
  const pct = Math.round((totalAnswered / 60) * 100);
  const blockComplete = blockDone === 10;
  const isLast = blockIdx === 5;
  const topRef = useRef(null);

  useEffect(() => { if (topRef.current) topRef.current.scrollTop = 0; }, [blockIdx]);

  return (
    <div className="fade-in" style={{ minHeight: '100vh', display: 'flex', flexDirection: 'column', background: 'var(--paper)' }}>
      {/* barra superior con progreso */}
      <header style={{ position: 'sticky', top: 0, zIndex: 10, background: 'var(--paper)', borderBottom: '1px solid var(--hair)' }}>
        <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', padding: '18px 48px' }}>
          <Brand small />
          <div style={{ display: 'flex', alignItems: 'center', gap: 18 }}>
            <span className="mono" style={{ fontSize: 12, color: 'var(--ink-3)' }}>{totalAnswered} / 60 respondidas</span>
            <div style={{ width: 8, height: 8, borderRadius: 8, background: 'var(--good)' }} title="Guardado automático"></div>
            <span className="mono" style={{ fontSize: 11, color: 'var(--ink-3)' }}>Guardado</span>
          </div>
        </div>
        <div style={{ height: 3, background: 'var(--paper-2)' }}>
          <div style={{ width: `${pct}%`, height: '100%', background: 'var(--gold)', transition: 'width .4s ease' }}></div>
        </div>
      </header>

      <div ref={topRef} style={{ flex: 1, overflowY: 'auto' }}>
        <div style={{ maxWidth: 760, margin: '0 auto', padding: '40px 48px 120px', width: '100%' }} key={blockIdx} className="fade-up">
          {/* cabecera de bloque (neutral, sin nombrar el arquetipo para no sesgar) */}
          <div style={{ display: 'flex', alignItems: 'center', gap: 16, marginBottom: 8 }}>
            <div style={{ width: 46, height: 46, borderRadius: 11, background: arch.hex + '18', display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
              <Glyph id={id} size={24} stroke={1.8} />
            </div>
            <div>
              <div className="eyebrow">Bloque {String(blockIdx + 1).padStart(2, '0')} de 06</div>
              <div className="serif" style={{ fontSize: 22, fontWeight: 600 }}>10 afirmaciones</div>
            </div>
          </div>
          <p style={{ fontSize: 14.5, color: 'var(--ink-2)', margin: '4px 0 30px', lineHeight: 1.5 }}>
            Indica con qué frecuencia te identificas con cada afirmación. Responde con honestidad: no hay respuestas correctas.
          </p>

          <div style={{ display: 'flex', flexDirection: 'column', gap: 10 }}>
            {qs.map((q, i) => (
              <QuestionRow key={i} idx={i} text={q} value={blockAnswers[i]} color={arch.hex}
                onChange={v => onAnswer(id, i, v)} />
            ))}
          </div>
        </div>
      </div>

      {/* footer navegación */}
      <footer className="no-print" style={{ position: 'sticky', bottom: 0, background: 'var(--paper)', borderTop: '1px solid var(--hair)', padding: '16px 48px', display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
        <button className="btn btn-ghost" onClick={() => blockIdx === 0 ? onBack() : setBlockIdx(blockIdx - 1)}>← {blockIdx === 0 ? 'Datos' : 'Bloque anterior'}</button>
        <div style={{ display: 'flex', gap: 6 }}>
          {ids.map((_, i) => {
            const done = (answers[ids[i]] || []).filter(Boolean).length === 10;
            return <div key={i} onClick={() => setBlockIdx(i)} style={{ width: 26, height: 5, borderRadius: 5, cursor: 'pointer',
              background: i === blockIdx ? 'var(--gold)' : done ? 'var(--ink-3)' : 'var(--hair-2)' }}></div>;
          })}
        </div>
        <button className="btn btn-primary" disabled={!blockComplete}
          onClick={() => isLast ? onFinish() : setBlockIdx(blockIdx + 1)}>
          {isLast ? 'Ver mi radiografía →' : 'Siguiente bloque →'}
        </button>
      </footer>
    </div>
  );
}

function QuestionRow({ idx, text, value, onChange, color }) {
  return (
    <div style={{ display: 'flex', alignItems: 'center', gap: 20, padding: '16px 20px', background: value ? 'var(--panel)' : 'var(--panel-soft)',
      border: '1px solid var(--hair)', borderRadius: 'var(--r)', transition: 'background .2s' }}>
      <span className="mono" style={{ fontSize: 12, color: 'var(--ink-3)', width: 20, flex: 'none' }}>{String(idx + 1).padStart(2, '0')}</span>
      <span style={{ flex: 1, fontSize: 15, lineHeight: 1.45, color: 'var(--ink)' }}>{text}</span>
      <div style={{ display: 'flex', gap: 7, flex: 'none' }}>
        {IHF.scaleLabels.map((lbl, v) => {
          const active = value === v + 1;
          return (
            <button key={v} onClick={() => onChange(v + 1)} title={lbl}
              style={{ width: 38, height: 38, borderRadius: 8, cursor: 'pointer', fontFamily: 'var(--mono)', fontSize: 13, fontWeight: 600,
                border: '1px solid ' + (active ? color : 'var(--hair-2)'),
                background: active ? color : 'var(--panel)', color: active ? '#fff' : 'var(--ink-3)',
                transition: 'all .14s' }}>
              {v + 1}
            </button>
          );
        })}
      </div>
    </div>
  );
}

/* ---------- Shell de pasos intermedios ---------- */
function FlowShell({ step, onBack, children }) {
  return (
    <div className="fade-in" style={{ minHeight: '100vh', display: 'flex', flexDirection: 'column' }}>
      <header style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', padding: '22px 48px', borderBottom: '1px solid var(--hair)' }}>
        <Brand small />
        <span className="eyebrow">{step}</span>
      </header>
      <div style={{ flex: 1, display: 'flex', flexDirection: 'column', justifyContent: 'center', padding: '56px 48px' }}>
        {children}
      </div>
    </div>
  );
}

/* ============================================================
   ScreenLogin — acceso al panel ejecutivo
   ============================================================ */
function ScreenLogin({ onSuccess, onBack }) {
  const [email, setEmail] = useState('');
  const [password, setPassword] = useState('');
  const [busy, setBusy] = useState(false);
  const [error, setError] = useState(null);

  const handleSubmit = async (e) => {
    e.preventDefault();
    if (!email || !password) return;
    setBusy(true);
    setError(null);
    try {
      const user = await IHA.login(email, password);
      onSuccess(user);
    } catch (err) {
      setError(err.message || 'Credenciales incorrectas');
    } finally {
      setBusy(false);
    }
  };

  return (
    <FlowShell step="Acceso ejecutivo" onBack={onBack}>
      <div className="fade-up" style={{ maxWidth: 420, margin: '0 auto', width: '100%' }}>
        <div className="eyebrow" style={{ marginBottom: 14 }}>Panel ejecutivo</div>
        <h2 className="serif" style={{ fontSize: 36, fontWeight: 500, margin: '0 0 12px', letterSpacing: '-0.01em' }}>Acceso restringido</h2>
        <p style={{ fontSize: 15, color: 'var(--ink-2)', margin: '0 0 36px', lineHeight: 1.55 }}>
          Ingresa con tu cuenta de administrador para ver el panel ejecutivo.
        </p>
        <form onSubmit={handleSubmit}>
          <div style={{ display: 'flex', flexDirection: 'column', gap: 18 }}>
            <div>
              <label className="eyebrow" style={{ display: 'block', marginBottom: 8, fontSize: 10.5 }}>Correo</label>
              <input type="email" value={email} onChange={e => setEmail(e.target.value)}
                placeholder="admin@empresa.com" className="ih-input" autoFocus />
            </div>
            <div>
              <label className="eyebrow" style={{ display: 'block', marginBottom: 8, fontSize: 10.5 }}>Contraseña</label>
              <input type="password" value={password} onChange={e => setPassword(e.target.value)}
                placeholder="••••••••" className="ih-input" />
            </div>
          </div>
          {error && (
            <div style={{ marginTop: 14, fontSize: 13, color: 'var(--risk)', background: 'oklch(0.56 0.13 28 / 0.08)', borderRadius: 8, padding: '10px 14px' }}>
              {error}
            </div>
          )}
          <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginTop: 32 }}>
            <button type="button" className="btn btn-ghost" onClick={onBack} style={{ fontSize: 13 }}>← Volver</button>
            <button type="submit" className="btn btn-primary" disabled={busy || !email || !password}
              style={{ fontSize: 15, padding: '14px 30px' }}>
              {busy ? 'Ingresando…' : 'Ingresar →'}
            </button>
          </div>
        </form>
        <style>{`
          .ih-input { width:100%; font-family:var(--sans); font-size:15px; color:var(--ink);
            background:var(--panel); border:1px solid var(--hair-2); border-radius:var(--r);
            padding:13px 15px; outline:none; transition:border-color .15s, box-shadow .15s; box-sizing:border-box; }
          .ih-input:focus { border-color:var(--gold); box-shadow:0 0 0 3px var(--gold-wash); }
        `}</style>
      </div>
    </FlowShell>
  );
}

Object.assign(window, { Brand, ScreenWelcome, ScreenDatos, ScreenEval, FlowShell, ScreenLogin });
