/* LOGIN — employee code + full name, or doctor email
   Dos modos: empleado (codigo + nombre) y profesional (correo corporativo).
   Acepta prop onLogin(user) -> lo invoca al autenticar con exito.
   Sin onLogin (canvas de diseno) funciona en modo visual solamente. */

/* Prefijos -> empresa (mirrors backend companyHelper) */
const COMPANY_MAP = { '1':'Polyec', '3':'Polinter', '4':'Lacoplast' };
function companyFromCode(code) {
  if (!code) return null;
  return COMPANY_MAP[code.split('-')[0]] ?? null;
}

function LoginView({ onLogin } = {}) {
  const [mode,     setMode]     = React.useState('employee'); /* employee | doctor */
  const [code,     setCode]     = React.useState('');
  const [fullName, setFullName] = React.useState('');
  const [email,    setEmail]    = React.useState('');
  const [pin,      setPin]      = React.useState('');
  const [remember, setRemember] = React.useState(true);
  const [loading,  setLoading]  = React.useState(false);
  const [apiError, setApiError] = React.useState(null);

  const company = React.useMemo(() => companyFromCode(code), [code]);

  const companyColor = {
    Polyec:    'text-sky-600',
    Polinter:  'text-mint-600',
    Lacoplast: 'text-amber-600',
  };

  async function handleSubmit() {
    if (!onLogin) return;
    setApiError(null);
    setLoading(true);

    try {
      if (mode === 'doctor') {
        if (!email.trim() || !pin.trim()) return;
        const res = await window.apiFetch('/api/auth/login-doctor', {
          method: 'POST',
          body: JSON.stringify({ email: email.trim(), pin: pin.trim() }),
        });
        const data = await res.json();
        if (!res.ok) throw new Error(data.error || 'Error al iniciar sesion.');
        onLogin({ ...data.professional, role: 'professional', type: 'professional' });
      } else {
        if (!code.trim() || !fullName.trim()) return;
        const res = await window.apiFetch('/api/auth/login', {
          method: 'POST',
          body: JSON.stringify({ code: code.trim(), full_name: fullName.trim() }),
        });
        const data = await res.json();
        if (!res.ok) throw new Error(data.error || 'Error al iniciar sesion.');
        onLogin({ ...data.employee, type: 'employee' });
      }
    } catch (err) {
      setApiError(err.message);
    } finally {
      setLoading(false);
    }
  }

  function handleKeyDown(e) {
    if (e.key === 'Enter') handleSubmit();
  }

  const canSubmit = mode === 'doctor'
    ? email.trim().length > 3 && pin.trim().length >= 4
    : code.trim().length >= 3 && fullName.trim().length >= 2;

  return (
    <div className="flex bg-midnight-950 min-h-screen font-sans text-ink">

      {/* LEFT: brand panel */}
      <aside className="w-[44%] relative overflow-hidden text-white p-12 flex flex-col">
        <div className="absolute -top-20 -left-20 h-[360px] w-[360px] rounded-full bg-mint-400/15 blur-3xl"/>
        <div className="absolute bottom-0 -right-32 h-[420px] w-[420px] rounded-full bg-midnight-600/40 blur-3xl"/>
        <div className="absolute inset-0 opacity-[0.06]"
             style={{backgroundImage:'linear-gradient(#fff 1px,transparent 1px),linear-gradient(90deg,#fff 1px,transparent 1px)', backgroundSize:'40px 40px'}}/>

        <div className="relative"><Logo tone="light"/></div>

        <div className="relative mt-auto">
          <div className="text-[11px] uppercase tracking-[0.18em] text-mint-300 font-medium">Servicio medico interno</div>
          <h2 className="text-[34px] font-semibold tracking-tight mt-3 leading-[1.1] max-w-[420px]">
            Tu salud, gestionada desde un solo lugar.
          </h2>
          <p className="text-white/60 text-[13.5px] mt-3 max-w-[400px] leading-relaxed">
            Reserva citas, consulta tu historial y recibe recordatorios. Cobertura corporativa para colaboradores y beneficiarios.
          </p>
          <div className="mt-10 grid grid-cols-3 gap-6">
            {[{n:'12+',l:'Especialidades'},{n:'24/7',l:'Telemedicina'},{n:'0',l:'Costo para ti'}].map((s,i)=>(
              <div key={i}>
                <div className="text-[22px] font-semibold tnum">{s.n}</div>
                <div className="text-[11px] text-white/50 mt-1">{s.l}</div>
              </div>
            ))}
          </div>
        </div>

        <div className="relative mt-12 flex items-center justify-between text-[11.5px] text-white/40">
          <div className="inline-flex items-center gap-2">
            <I.shield className="h-3.5 w-3.5 text-mint-400"/>HIPAA, Ley 1581
          </div>
          <div>v 1.0.4, MVP</div>
        </div>
      </aside>

      {/* RIGHT: form */}
      <main className="flex-1 bg-paper grid place-items-center p-10">
        <div className="w-[440px]">
          {/* Mode tabs */}
          <div className="flex gap-1 p-1 rounded-xl bg-midnight-50/60 ring-1 ring-line mb-7">
            <button
              onClick={() => { setMode('employee'); setApiError(null); }}
              className={`flex-1 h-9 rounded-lg text-[12.5px] font-medium transition
                ${mode==='employee' ? 'bg-white text-midnight-900 shadow-sm' : 'text-slate-500 hover:text-midnight-700'}`}>
              Empleado
            </button>
            <button
              onClick={() => { setMode('doctor'); setApiError(null); }}
              className={`flex-1 h-9 rounded-lg text-[12.5px] font-medium transition
                ${mode==='doctor' ? 'bg-white text-midnight-900 shadow-sm' : 'text-slate-500 hover:text-midnight-700'}`}>
              Profesional medico
            </button>
          </div>

          <div className="text-[11px] uppercase tracking-[0.16em] text-mint-600 font-medium">Iniciar sesion</div>
          <h1 className="text-[28px] font-semibold tracking-tight text-midnight-900 mt-2 leading-tight">
            {mode === 'doctor'
              ? <>Ingresa con tu correo<br/>corporativo.</>
              : <>Ingresa con tu codigo<br/>de empleado.</>
            }
          </h1>
          <p className="text-[13px] text-slate-500 mt-3">
            {mode === 'doctor'
              ? 'Usamos tu correo @polytec.com.gt registrado en el sistema.'
              : 'Usamos tu codigo corporativo y nombre completo como verificacion.'
            }
          </p>

          <div className="mt-8 space-y-5">

            {mode === 'employee' ? (
              <>
                {/* Campo 1: Codigo de empleado */}
                <div>
                  <label className="text-[12px] font-medium text-midnight-800">Codigo de empleado</label>
                  <div className="mt-1.5 relative">
                    <input
                      value={code}
                      onChange={e => { setCode(e.target.value); setApiError(null); }}
                      onKeyDown={handleKeyDown}
                      className="w-full h-12 rounded-xl bg-white ring-1 ring-line px-4 pr-28 text-[15px] font-medium tnum text-midnight-900 placeholder:text-slate-300 focus:outline-none focus:ring-midnight-400 transition"
                      placeholder="ej: 3-4148"
                      autoComplete="username"
                      spellCheck="false"/>
                    {company ? (
                      <span className={`absolute right-3 top-1/2 -translate-y-1/2 text-[10.5px] font-semibold inline-flex items-center gap-1 ${companyColor[company]}`}>
                        <I.check className="h-3.5 w-3.5"/>{company}
                      </span>
                    ) : code.length > 0 ? (
                      <span className="absolute right-3 top-1/2 -translate-y-1/2 text-[10.5px] text-rose-400 font-medium">
                        Prefijo invalido
                      </span>
                    ) : null}
                  </div>
                  <div className="text-[11.5px] text-slate-400 mt-1.5">
                    Formato: <span className="tnum font-medium text-slate-500">1-XXXX</span> Polyec, <span className="tnum font-medium text-slate-500">3-XXXX</span> Polinter, <span className="tnum font-medium text-slate-500">4-XXXX</span> Lacoplast
                  </div>
                </div>

                {/* Campo 2: Nombre completo */}
                <div>
                  <label className="text-[12px] font-medium text-midnight-800">Nombre completo</label>
                  <div className="mt-1.5 relative">
                    <I.user className="h-4 w-4 absolute left-3.5 top-1/2 -translate-y-1/2 text-slate-400 pointer-events-none"/>
                    <input
                      value={fullName}
                      onChange={e => { setFullName(e.target.value); setApiError(null); }}
                      onKeyDown={handleKeyDown}
                      className="w-full h-12 rounded-xl bg-white ring-1 ring-line pl-10 pr-4 text-[15px] font-medium text-midnight-900 placeholder:text-slate-300 focus:outline-none focus:ring-midnight-400 transition"
                      placeholder="ej: Valentina Aguirre"
                      autoComplete="name"
                      spellCheck="false"/>
                  </div>
                  <div className="text-[11.5px] text-slate-400 mt-1.5">
                    Debe coincidir exactamente con tu registro corporativo.
                  </div>
                </div>
              </>
            ) : (
              <>
              {/* Campo doctor: correo */}
              <div>
                <label className="text-[12px] font-medium text-midnight-800">Correo corporativo</label>
                <div className="mt-1.5 relative">
                  <svg viewBox="0 0 24 24" className="h-4 w-4 absolute left-3.5 top-1/2 -translate-y-1/2 text-slate-400 pointer-events-none" fill="none">
                    <rect x="3" y="5" width="18" height="14" rx="2" stroke="currentColor" strokeWidth="1.6"/>
                    <path d="m3 7 9 6 9-6" stroke="currentColor" strokeWidth="1.6"/>
                  </svg>
                  <input
                    value={email}
                    onChange={e => { setEmail(e.target.value); setApiError(null); }}
                    onKeyDown={handleKeyDown}
                    type="email"
                    className="w-full h-12 rounded-xl bg-white ring-1 ring-line pl-10 pr-4 text-[15px] font-medium text-midnight-900 placeholder:text-slate-300 focus:outline-none focus:ring-midnight-400 transition"
                    placeholder="ej: helena.restrepo@polytec.com.gt"
                    autoComplete="email"
                    spellCheck="false"/>
                </div>
                <div className="text-[11.5px] text-slate-400 mt-1.5">
                  El correo registrado como tu Google Calendar ID en el sistema.
                </div>
              </div>

              {/* Campo doctor: PIN */}
              <div>
                <label className="text-[12px] font-medium text-midnight-800">PIN de acceso</label>
                <div className="mt-1.5 relative">
                  <I.shield className="h-4 w-4 absolute left-3.5 top-1/2 -translate-y-1/2 text-slate-400 pointer-events-none"/>
                  <input
                    value={pin}
                    onChange={e => { const v = e.target.value.replace(/\D/g,'').slice(0,6); setPin(v); setApiError(null); }}
                    onKeyDown={handleKeyDown}
                    type="password"
                    inputMode="numeric"
                    maxLength={6}
                    className="w-full h-12 rounded-xl bg-white ring-1 ring-line pl-10 pr-4 text-[15px] font-medium text-midnight-900 placeholder:text-slate-300 focus:outline-none focus:ring-midnight-400 transition tracking-[0.3em]"
                    placeholder="****"
                    autoComplete="current-password"/>
                </div>
                <div className="text-[11.5px] text-slate-400 mt-1.5">
                  PIN de 4 a 6 digitos asignado por el administrador.
                </div>
              </div>
              </>
            )}

            {/* Error de API */}
            {apiError && (
              <div className="flex items-start gap-2.5 bg-rose-50 ring-1 ring-rose-200 text-rose-700 text-[12.5px] px-4 py-3 rounded-xl">
                <svg className="h-4 w-4 shrink-0 mt-0.5" fill="none" stroke="currentColor" strokeWidth="2" viewBox="0 0 24 24">
                  <path strokeLinecap="round" strokeLinejoin="round" d="M12 9v4m0 4h.01M10.29 3.86L1.82 18a2 2 0 001.71 3h16.94a2 2 0 001.71-3L13.71 3.86a2 2 0 00-3.42 0z"/>
                </svg>
                <span>{apiError}</span>
              </div>
            )}

            {/* Recordar equipo */}
            <label className="flex items-start gap-2.5 cursor-pointer select-none">
              <button
                type="button"
                onClick={() => setRemember(r => !r)}
                className={`mt-0.5 h-4 w-4 rounded-[5px] grid place-items-center transition ring-1
                  ${remember ? 'bg-midnight-900 ring-midnight-900' : 'bg-white ring-slate-300'}`}>
                {remember && <I.check className="h-3 w-3 text-mint-300"/>}
              </button>
              <div>
                <div className="text-[12.5px] text-midnight-800 font-medium leading-tight">Recordar este equipo</div>
                <div className="text-[11.5px] text-slate-500 mt-0.5">No marques esta opcion en equipos compartidos o de sala comun.</div>
              </div>
            </label>

            {/* Boton principal */}
            <button
              onClick={handleSubmit}
              disabled={loading || !canSubmit}
              className="w-full h-12 rounded-xl bg-midnight-900 text-white text-[14px] font-semibold hover:bg-midnight-800 transition flex items-center justify-center gap-2 disabled:opacity-50 disabled:cursor-not-allowed">
              {loading ? (
                <>
                  <svg className="h-4 w-4 animate-spin" fill="none" viewBox="0 0 24 24">
                    <circle className="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" strokeWidth="4"/>
                    <path className="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4z"/>
                  </svg>
                  Verificando...
                </>
              ) : (
                <>Continuar <I.chevR className="h-4 w-4"/></>
              )}
            </button>
          </div>

          <div className="mt-7 pt-6 border-t border-line flex items-center justify-between text-[12px]">
            <a className="text-slate-500 hover:text-midnight-700 cursor-pointer">Olvidaste tu codigo?</a>
            <a className="text-midnight-700 font-medium hover:text-midnight-900 inline-flex items-center gap-1 cursor-pointer">
              Soporte interno <I.chevR className="h-3 w-3"/>
            </a>
          </div>
        </div>
      </main>
    </div>
  );
}

window.LoginView = LoginView;
