const { useState: useStateLogin, useEffect: useEffectLogin } = React;

/* ─── Valores por defecto del panel de inicio ─────────────────────────── */
var DEFAULT_HP_SETTINGS = {
  descripcion: 'Plataforma oficial de entrenamiento especializado en Emprendimiento, Diseño y Automatización del SG-SST. Alineada 100% a la normativa colombiana vigente.',
  contador1Num: '+1.000',
  contador1Desc: 'Profesionales SST formados',
  contador2Num: '+200',
  contador2Desc: 'Plantillas editables',
  calificacionNum: '4.9/5',
  calificacionDesc: 'Calificación promedio de nuestros estudiantes',
  testimonio1Texto: 'Este entrenamiento cambió completamente mi forma de diseñar el SG-SST. Ahora trabajo en la mitad del tiempo.',
  testimonio1Nombre: 'Lina M.',
  testimonio1Cargo: 'Técnica SST',
  testimonio1Empresa: 'SONESTA',
  testimonio2Texto: 'Por fin un curso que enseña SST con herramientas reales e IA. Totalmente recomendado.',
  testimonio2Nombre: 'Andrés G.',
  testimonio2Cargo: 'Profesional SST',
  testimonio2Empresa: '',
  testimonio3Texto: 'Gracias a ASSYST conseguí mi primer cliente corporativo al mes de terminar.',
  testimonio3Nombre: 'María T.',
  testimonio3Cargo: 'Consultora Independiente',
  testimonio3Empresa: '',
  badge1: '✓ Certificado ASSYST',
  badge2: '✓ 100% Virtual',
  badge3: '✓ Normativa vigente 2025',
  mensajeBienvenida: 'Nos alegra tenerte de vuelta. Ingresa con tus credenciales para continuar tu entrenamiento.'
};
window.DEFAULT_HP_SETTINGS = DEFAULT_HP_SETTINGS;

function getHPSettings() {
  try {
    var s = localStorage.getItem('sst_homepage_settings');
    if (s) return Object.assign({}, DEFAULT_HP_SETTINGS, JSON.parse(s));
  } catch (e) {}
  return Object.assign({}, DEFAULT_HP_SETTINGS);
}
window.getHPSettings = getHPSettings;

/* ─── Pantalla de Login ───────────────────────────────────────────────── */
function LoginScreen({ onLogin }) {
  const [email, setEmail] = useStateLogin('');
  const [pw, setPw] = useStateLogin('');
  const [err, setErr] = useStateLogin('');
  const [busy, setBusy] = useStateLogin(false);
  const [hp, setHp] = useStateLogin(getHPSettings);

  /* Escucha cambios guardados por el admin en la misma pestaña */
  useEffectLogin(function () {
    function onHpUpdate() { setHp(getHPSettings()); }
    window.addEventListener('sst_homepage_updated', onHpUpdate);
    return function () { window.removeEventListener('sst_homepage_updated', onHpUpdate); };
  }, []);

  function submit(e) {
    e.preventDefault(); setErr(''); setBusy(true);
    if (typeof window.sbSignIn === 'function') {
      window.sbSignIn(email, pw).then(function (res) {
        if (res.error) { setErr('Correo o contraseña incorrectos'); setBusy(false); return; }
        var uid = res.data.user.id;
        window.sbGetProfile(uid).then(function (pRes) {
          if (pRes.error || !pRes.data) { setErr('No se encontró el perfil del usuario'); setBusy(false); return; }
          var profile = pRes.data;
          if (!profile.activo) { setErr('Tu cuenta está desactivada. Contacta al administrador.'); setBusy(false); window.sbSignOut(); return; }
          var u = { id: profile.id, nombre: profile.nombre, email: profile.email, rol: profile.rol, empresa: profile.empresa || '', cargo: profile.cargo || '', activo: profile.activo, fechaCreacion: profile.fecha_creacion || '' };
          window.sbLoadAll().then(function () { onLogin(u); });
        });
      });
    } else {
      setTimeout(function () {
        var u = getUsers().find(function (x) { return x.email === email && x.password === pw && x.activo; });
        if (u) { onLogin(u); } else { setErr('Correo o contraseña incorrectos'); setBusy(false); }
      }, 600);
    }
  }

  var inp = {
    width: '100%', padding: '11px 16px', border: '1.5px solid #e5e7eb',
    borderRadius: 8, fontSize: 14, fontFamily: 'inherit', outline: 'none',
    boxSizing: 'border-box', background: '#fafafa', color: '#1e293b'
  };



  return (
    <div className="sst-login-wrap" style={{ display: 'flex', minHeight: '100vh', fontFamily: "'Montserrat',sans-serif" }}>

      {/* ─── LEFT: Formulario ───────────────────────────── */}
      <div className="sst-login-form" style={{ width: 460, background: '#F7F9FC', display: 'flex', alignItems: 'center', justifyContent: 'center', padding: '48px 40px', flexShrink: 0 }}>
        <div style={{ width: '100%', maxWidth: 360 }}>
          <h2 style={{ fontSize: 28, fontWeight: 800, color: '#1c79b4', margin: '0 0 8px' }}>Bienvenido</h2>
          <p style={{ fontSize: 14, color: '#6b7280', margin: '0 0 30px', lineHeight: 1.55 }}>{hp.mensajeBienvenida}</p>

          <form onSubmit={submit}>
            <div style={{ marginBottom: 18 }}>
              <label style={{ display: 'block', fontSize: 11, fontWeight: 700, color: '#374151', marginBottom: 7, textTransform: 'uppercase', letterSpacing: '0.07em' }}>Correo electrónico</label>
              <input style={inp} type="email" value={email} onChange={function (e) { setEmail(e.target.value); }} placeholder="tu@empresa.com" required />
            </div>
            <div style={{ marginBottom: 24 }}>
              <label style={{ display: 'block', fontSize: 11, fontWeight: 700, color: '#374151', marginBottom: 7, textTransform: 'uppercase', letterSpacing: '0.07em' }}>Contraseña</label>
              <input style={inp} type="password" value={pw} onChange={function (e) { setPw(e.target.value); }} placeholder="••••••••" required />
            </div>
            {err && <div style={{ background: '#fef2f2', border: '1px solid #fca5a5', borderRadius: 8, padding: '10px 14px', color: '#dc2626', fontSize: 13, marginBottom: 16 }}>{err}</div>}
            <button type="submit" disabled={busy} style={{ width: '100%', padding: '14px', background: busy ? '#94a3b8' : '#1c79b4', color: 'white', border: 'none', borderRadius: 10, fontSize: 15, fontWeight: 700, cursor: busy ? 'wait' : 'pointer', fontFamily: 'inherit', letterSpacing: '0.02em', transition: 'background .2s' }}>
              {busy ? 'Verificando...' : 'Iniciar sesión →'}
            </button>
          </form>

          <div style={{ marginTop: 16, padding: '13px 16px', background: '#f0f7ff', border: '1px solid #c3ddf5', borderLeft: '3px solid #1c79b4', borderRadius: '0 8px 8px 0', display: 'flex', gap: 10, alignItems: 'flex-start' }}>
            <div style={{ width: 18, height: 18, borderRadius: '50%', background: '#1c79b4', color: 'white', fontSize: 11, fontWeight: 800, display: 'flex', alignItems: 'center', justifyContent: 'center', flexShrink: 0, marginTop: 1 }}>i</div>
            <p style={{ margin: 0, fontSize: 12, color: '#3d6a91', lineHeight: 1.6 }}>
              Ingresa con las credenciales que te proporcionó tu administrador. Si aún no tienes acceso, contacta al administrador del entrenamiento.
            </p>
          </div>
        </div>
      </div>

      {/* ─── RIGHT: Panel de marca ──────────────────────── */}
      <div className="sst-login-brand" style={{ flex: 1, background: 'linear-gradient(148deg,#0a3d5e 0%,#1c79b4 45%,#1e6fa3 100%)', display: 'flex', flexDirection: 'column', position: 'relative', overflow: 'hidden' }}>

        {/* Anillos decorativos */}
        <div style={{ position: 'absolute', top: 120, right: -100, width: 420, height: 420, borderRadius: '50%', border: '1px solid rgba(196,180,0,.10)', pointerEvents: 'none' }} />
        <div style={{ position: 'absolute', bottom: -160, left: -80, width: 500, height: 500, borderRadius: '50%', border: '1px solid rgba(196,180,0,.06)', pointerEvents: 'none' }} />

        {/* Logo header fijo */}
        <div style={{ background: 'white', display: 'flex', alignItems: 'center', justifyContent: 'center', padding: '28px 40px', boxShadow: '0 3px 16px rgba(0,0,0,.12)', position: 'relative', zIndex: 2, flexShrink: 0 }}>
          <img src={(window.__resources && window.__resources.logoAssyst) || "uploads/LOGO.png"} alt="ASSYST" style={{ width: 130, height: 130, objectFit: 'contain', display: 'block' }} />
        </div>

        {/* Contenido scrollable */}
        <div style={{ flex: 1, overflowY: 'auto', padding: '38px 48px 36px', position: 'relative', zIndex: 1 }}>

          {/* Título principal */}
          <h1 style={{ color: '#ffffff', fontSize: 34, fontWeight: 900, lineHeight: 1.15, margin: '0 0 10px', textShadow: '0 2px 8px rgba(0,0,0,.22)' }}>
            Formación en <span style={{ color: '#c4b400' }}>Seguridad</span><br />y Salud en el Trabajo
          </h1>

          {/* Descripción editable */}
          <p style={{ color: 'rgba(255,255,255,.88)', fontSize: 15, lineHeight: 1.65, margin: '0 0 22px', fontWeight: 500 }}>
            {hp.descripcion}
          </p>

          {/* Contadores */}
          <div style={{ display: 'flex', gap: 36, marginBottom: 18 }}>
            {[[hp.contador1Num, hp.contador1Desc], [hp.contador2Num, hp.contador2Desc]].map(function (c) {
              return (
                <div key={c[1]}>
                  <div style={{ color: '#c4b400', fontSize: 38, fontWeight: 900, lineHeight: 1 }}>{c[0]}</div>
                  <div style={{ color: 'rgba(255,255,255,.72)', fontSize: 12, marginTop: 6, textTransform: 'uppercase', letterSpacing: '0.09em', fontWeight: 600 }}>{c[1]}</div>
                </div>
              );
            })}
          </div>

          {/* Rating */}
          <div style={{ display: 'inline-flex', alignItems: 'center', gap: 8, background: 'rgba(196,180,0,.13)', border: '1px solid rgba(196,180,0,.38)', borderRadius: 20, padding: '6px 16px', marginBottom: 22 }}>
            <span style={{ fontSize: 14 }}>⭐</span>
            <span style={{ color: '#c4b400', fontWeight: 800, fontSize: 16 }}>{hp.calificacionNum}</span>
            <span style={{ color: 'rgba(255,255,255,.7)', fontSize: 13 }}>— {hp.calificacionDesc}</span>
          </div>



          {/* Badges de confianza */}
          <div style={{ display: 'flex', gap: 8, flexWrap: 'wrap', marginBottom: 24 }}>
            {[hp.badge1, hp.badge2, hp.badge3].filter(Boolean).map(function (b) {
              return (
                <span key={b} style={{ background: 'rgba(196,180,0,.12)', border: '1px solid rgba(196,180,0,.45)', color: '#c4b400', borderRadius: 20, padding: '7px 16px', fontSize: 13, fontWeight: 700 }}>{b}</span>
              );
            })}
          </div>

          {/* Huellitas en Acción */}
          <div onClick={function () { window.openHuellitasModal(); }} style={{ background: 'white', borderRadius: 14, overflow: 'hidden', boxShadow: '0 6px 28px rgba(0,0,0,.22)', cursor: 'pointer' }}>
            <div style={{ padding: '14px 16px' }}>
              <div style={{ display: 'flex', alignItems: 'center', gap: 6, marginBottom: 7 }}>
                <span style={{ fontSize: 16 }}>🐾</span>
                <span style={{ color: '#1c79b4', fontWeight: 800, fontSize: 12, textTransform: 'uppercase', letterSpacing: '0.07em' }}>Huellitas en Acción</span>
              </div>
              <p style={{ fontSize: 14, color: '#374151', lineHeight: 1.55, margin: '0 0 8px' }}>Por cada estudiante inscrito, destinamos parte de los ingresos a alimentar y cuidar perros y gatos en abandono.</p>
              <div style={{ background: '#EBF5FF', borderLeft: '3px solid #1c79b4', padding: '7px 10px', borderRadius: '0 6px 6px 0', marginBottom: 7 }}>
                <div style={{ fontSize: 10, fontWeight: 700, color: '#1c79b4', textTransform: 'uppercase' }}>Convirtamos cada aprendizaje en un plato lleno.</div>
              </div>
              <div style={{ fontSize: 11, fontWeight: 900, color: '#1c79b4', textTransform: 'uppercase', marginBottom: 3 }}>Cuando tú creces, ellos también ganan.</div>
              <div style={{ fontSize: 10, fontStyle: 'italic', color: '#9ca3af' }}>Gracias por ser parte de esta causa.</div>
            </div>
          </div>

        </div>
      </div>

    </div>
  );
}

window.LoginScreen = LoginScreen;
