// ===== Login screen =====
function Login({ onLogin, showDemo }){
  const [user, setUser] = React.useState("");
  const [pass, setPass] = React.useState("");
  const [err, setErr] = React.useState("");
  const [show, setShow] = React.useState(false);
  const [loading, setLoading] = React.useState(false);

  // accounts come from the managed user list (Configuración → Usuarios)
  const users = loadUsers();

  function submit(e){
    e.preventDefault();
    if(!user.trim() || !pass){ setErr("Ingresa tu usuario y contraseña."); return; }
    setErr(""); setLoading(true);
    // Modo online: autentica contra el servidor (Cloudflare).
    if(window.CP_API && CP_API.online){
      CP_API.login(user.trim().toLowerCase(), pass).then(u=>{
        onLogin({ name:u.name, role:(ROLES[u.roleId]||{}).label||u.roleId, roleId:u.roleId,
          techId:u.id, username:u.username, initials:u.initials, hue:u.hue });
      }).catch(err=>{
        setLoading(false);
        setErr(String(err.message||"")==="inactive" ? "Esta cuenta está inactiva. Contacta al administrador." : "Usuario o contraseña incorrectos.");
      });
      return;
    }
    // Modo offline (preview / sin backend): validación local.
    const u = users.find(x => x.username === user.trim().toLowerCase());
    if(!u || u.pass !== pass){ setLoading(false); setErr("Usuario o contraseña incorrectos."); return; }
    if(!u.active){ setLoading(false); setErr("Esta cuenta está inactiva. Contacta al administrador."); return; }
    setTimeout(()=> onLogin({
      name: u.name, role: ROLES[u.roleId].label, roleId: u.roleId,
      techId: u.id, username: u.username, initials: u.initials, hue: u.hue,
    }), 650);
  }

  function quick(username){
    const u = users.find(x => x.username === username);
    if(u){ setUser(u.username); setPass(u.pass); setErr(""); }
  }

  return (
    <div style={{ minHeight:"100%", display:"grid", gridTemplateColumns:"1.05fr 1fr", background:"var(--surface)" }}>
      {/* Brand panel */}
      <div style={{
        position:"relative", overflow:"hidden", color:"#fff",
        background:"linear-gradient(150deg, oklch(0.42 0.13 262) 0%, oklch(0.5 0.16 256) 55%, oklch(0.56 0.15 248) 100%)",
        display:"flex", flexDirection:"column", justifyContent:"space-between", padding:"48px 52px",
      }}>
        {/* texture */}
        <div style={{ position:"absolute", inset:0, opacity:0.5,
          background:"radial-gradient(900px 500px at 80% -10%, oklch(0.7 0.15 248 / .5), transparent 60%), radial-gradient(700px 500px at -10% 110%, oklch(0.35 0.1 270 / .6), transparent 55%)" }} />
        <div style={{ position:"absolute", inset:0, opacity:0.07,
          backgroundImage:"linear-gradient(#fff 1px, transparent 1px), linear-gradient(90deg, #fff 1px, transparent 1px)", backgroundSize:"46px 46px" }} />

        <div style={{ position:"relative", display:"flex", alignItems:"center", gap:11 }}>
          <Logo light />
        </div>

        <div style={{ position:"relative" }}>
          <div style={{ fontSize:13, fontWeight:600, letterSpacing:"0.14em", textTransform:"uppercase", opacity:0.7, marginBottom:18 }}>
            Gestión de taller
          </div>
          <h1 style={{ fontSize:40, lineHeight:1.12, fontWeight:800, margin:0, letterSpacing:"-0.02em", maxWidth:480 }}>
            Toda orden de ingreso, bajo control.
          </h1>
          <p style={{ fontSize:16, lineHeight:1.6, opacity:0.82, marginTop:18, maxWidth:430 }}>
            Recibe, diagnostica y entrega reparaciones de celulares, laptops, drones y más — con seguimiento de cada equipo de principio a fin.
          </p>
          <div style={{ display:"flex", gap:28, marginTop:36 }}>
            {[["122","Órdenes activas"],["98%","Entregas a tiempo"],["6","Técnicos"]].map(([n,l])=>(
              <div key={l}>
                <div style={{ fontSize:30, fontWeight:800, letterSpacing:"-0.02em" }} className="mono">{n}</div>
                <div style={{ fontSize:13, opacity:0.75, marginTop:2 }}>{l}</div>
              </div>
            ))}
          </div>
        </div>

        <div style={{ position:"relative", fontSize:13, opacity:0.7 }}>© 2026 Casepoint · Taller de reparaciones</div>
      </div>

      {/* Form panel */}
      <div style={{ display:"flex", alignItems:"center", justifyContent:"center", padding:"40px" }}>
        <form onSubmit={submit} style={{ width:"100%", maxWidth:380, animation:"fadeUp .5s ease" }}>
          <div style={{ marginBottom:30 }}>
            <h2 style={{ fontSize:26, fontWeight:800, margin:"0 0 8px", letterSpacing:"-0.02em" }}>Iniciar sesión</h2>
            <p style={{ fontSize:14.5, color:"var(--muted)", margin:0 }}>Ingresa con tu cuenta del taller.</p>
          </div>

          <div style={{ display:"flex", flexDirection:"column", gap:16 }}>
            <Field label="Usuario">
              <div style={{ position:"relative" }}>
                <span style={{ position:"absolute", left:12, top:"50%", transform:"translateY(-50%)", color:"var(--faint)" }}><Icon name="user" size={18} /></span>
                <TextInput value={user} onChange={e=>setUser(e.target.value)} placeholder="ej. daniela" autoFocus
                  style={{ paddingLeft:38 }} autoComplete="username" />
              </div>
            </Field>

            <Field label="Contraseña">
              <div style={{ position:"relative" }}>
                <span style={{ position:"absolute", left:12, top:"50%", transform:"translateY(-50%)", color:"var(--faint)" }}><Icon name="settings" size={18} /></span>
                <TextInput type={show?"text":"password"} value={pass} onChange={e=>setPass(e.target.value)} placeholder="••••••••"
                  style={{ paddingLeft:38, paddingRight:64 }} autoComplete="current-password" />
                <button type="button" onClick={()=>setShow(s=>!s)}
                  style={{ position:"absolute", right:8, top:"50%", transform:"translateY(-50%)", border:"none", background:"transparent", color:"var(--muted)", fontSize:12.5, fontWeight:600, padding:"4px 8px" }}>
                  {show?"Ocultar":"Ver"}
                </button>
              </div>
            </Field>

            {err && (
              <div style={{ display:"flex", alignItems:"center", gap:8, padding:"10px 12px", borderRadius:10, background:"var(--danger-soft)", color:"var(--danger)", fontSize:13, fontWeight:500, animation:"fadeIn .2s" }}>
                <Icon name="warning" size={16} /> {err}
              </div>
            )}

            <div style={{ display:"flex", alignItems:"center", justifyContent:"space-between", fontSize:13 }}>
              <label style={{ display:"flex", alignItems:"center", gap:7, color:"var(--ink-2)", cursor:"pointer" }}>
                <input type="checkbox" defaultChecked style={{ accentColor:"var(--accent)", width:15, height:15 }} /> Recordarme en este equipo
              </label>
            </div>

            <Btn type="submit" size="lg" iconRight={loading?null:"arrowRight"} style={{ width:"100%", marginTop:4 }} disabled={loading}>
              {loading ? "Ingresando…" : "Entrar al taller"}
            </Btn>
          </div>

          {showDemo && (
          <div style={{ marginTop:26, paddingTop:20, borderTop:"1px solid var(--line)" }}>
            <div style={{ fontSize:12, fontWeight:600, color:"var(--faint)", textTransform:"uppercase", letterSpacing:"0.08em", marginBottom:10 }}>Cuentas de demostración</div>
            <div style={{ display:"flex", flexDirection:"column", gap:8 }}>
              {[["daniela","Técnico sénior"],["recepcion","Recepción"],["admin","Administrador"]].map(([u,r])=>(
                <button key={u} type="button" onClick={()=>quick(u)}
                  style={{ display:"flex", alignItems:"center", justifyContent:"space-between", padding:"9px 12px", borderRadius:9, border:"1px solid var(--line)", background:"var(--surface-2)", textAlign:"left", transition:"border-color .15s" }}
                  onMouseEnter={e=>e.currentTarget.style.borderColor="var(--accent)"}
                  onMouseLeave={e=>e.currentTarget.style.borderColor="var(--line)"}>
                  <span style={{ display:"flex", alignItems:"center", gap:9 }}>
                    <span className="mono" style={{ fontSize:13, fontWeight:600, color:"var(--ink)" }}>{u}</span>
                    <span style={{ fontSize:12, color:"var(--muted)" }}>{r}</span>
                  </span>
                  <span style={{ fontSize:11.5, color:"var(--faint)", fontWeight:600 }}>Usar →</span>
                </button>
              ))}
            </div>
          </div>
          )}
        </form>
      </div>
    </div>
  );
}

// Wordmark logo
function Logo({ light, size = 1 }){
  const ink = light ? "#fff" : "var(--ink)";
  return (
    <div style={{ display:"inline-flex", alignItems:"center", gap:10*size }}>
      <div style={{ width:32*size, height:32*size, borderRadius:9*size, position:"relative",
        background: light ? "#fff" : "var(--accent)",
        display:"flex", alignItems:"center", justifyContent:"center", boxShadow: light?"none":"var(--shadow-sm)" }}>
        <Icon name="tools" size={19*size} style={{ color: light ? "var(--accent)" : "#fff" }} />
      </div>
      <span style={{ fontSize:21*size, fontWeight:800, letterSpacing:"-0.03em", color:ink }}>
        Case<span style={{ opacity:0.62 }}>point</span>
      </span>
    </div>
  );
}

Object.assign(window, { Login, Logo });
