/* ============ Login (persona simulation) ============
   POC sign-in with a realistic email / password form. No real auth — the
   small "quick fill" buttons (bottom-right) drop in the credentials for one of
   three personas (Admin / Supervisor / Staff). Sign in matches the email to
   a seeded user and hands it up to App, which sets CURRENT_ADMIN.
   (Email replaced the separate username as the login identifier — user decision
   2026-06-12; the old username still works as a silent fallback.) */

const DEMO_PASSWORD = "demo1234";
const LOGIN_PERSONAS = [
  { role: "Admin",      short: "Admin" },
  { role: "Supervisor", short: "Sup." },
  { role: "Staff",      short: "Staff" },
];

const LoginScreen = ({ onLogin }) => {
  const users = (typeof USERS !== "undefined" ? USERS : []);
  const personaFor = (role) => users.find(u => u.role === role && u.active !== false) || users.find(u => u.role === role);

  const [loginId, setLoginId]   = React.useState("");
  const [password, setPassword] = React.useState("");
  const [showPw, setShowPw]     = React.useState(false);
  const [error, setError]       = React.useState("");

  const submit = () => {
    const term = loginId.trim().toLowerCase();
    const u = users.find(x =>
      ((x.email || "").toLowerCase() === term || x.username.toLowerCase() === term) && x.active !== false);
    if (!u)        { setError("Unknown email."); return; }
    if (!password) { setError("Enter your password."); return; }
    onLogin(u);
  };
  const quickFill = (role) => {
    const u = personaFor(role);
    if (u) { setLoginId(u.email || u.username); setPassword(DEMO_PASSWORD); setError(""); }
  };
  const onKey = (e) => { if (e.key === "Enter") submit(); };

  return (
    <div style={{minHeight:"100vh",display:"grid",placeItems:"center",background:"var(--bg)",padding:24}}>
      <div style={{width:"100%",maxWidth:380}}>
        {/* Brand */}
        <div style={{display:"flex",alignItems:"center",gap:12,marginBottom:22,justifyContent:"center"}}>
          <div className="logo" style={{width:40,height:40,borderRadius:9,fontSize:13}}>ASV</div>
          <div>
            <div style={{fontSize:17,fontWeight:600,letterSpacing:"-.01em"}}>Audit Safe Vault</div>
            <div className="mono" style={{fontSize:10.5,color:"var(--muted)",textTransform:"uppercase",letterSpacing:".06em"}}>TumWebSME · PIP2</div>
          </div>
        </div>

        <div className="card">
          <div className="card-head">
            <div className="card-title"><Icon n="lock" s={14}/> Sign in</div>
          </div>
          <div className="card-body" style={{display:"flex",flexDirection:"column",gap:14}}>
            <div className="field" style={{marginBottom:0}}>
              <label>Email</label>
              <input type="email" value={loginId} autoFocus
                onChange={e=>{setLoginId(e.target.value); setError("");}} onKeyDown={onKey}
                placeholder="e.g. praewa@tumweb.co.th"/>
            </div>
            <div className="field" style={{marginBottom:0}}>
              <label>Password</label>
              <div className="pw-wrap">
                <input type={showPw ? "text" : "password"} value={password}
                  onChange={e=>{setPassword(e.target.value); setError("");}} onKeyDown={onKey}
                  placeholder="••••••••"/>
                <button type="button" className="pw-toggle"
                  onClick={()=>setShowPw(v=>!v)}
                  title={showPw ? "Hide password" : "Show password"}
                  aria-label={showPw ? "Hide password" : "Show password"}>
                  <Icon n={showPw ? "eye-off" : "eye"} s={15}/>
                </button>
              </div>
            </div>

            {error && <div className="err"><Icon n="alert" s={12}/> {error}</div>}

            <button className="btn primary" style={{width:"100%",justifyContent:"center"}}
              disabled={!loginId || !password} onClick={submit}>
              <Icon n="log-out" s={13}/> Sign in
            </button>

            {/* Quick fill — drops in demo credentials for a role */}
            <div style={{display:"flex",alignItems:"center",justifyContent:"flex-end",gap:6,marginTop:2}}>
              <span style={{fontSize:10.5,color:"var(--muted-2)"}}>Quick fill:</span>
              {LOGIN_PERSONAS.map(p => (
                <button key={p.role} className="btn ghost sm" style={{padding:"2px 7px",fontSize:11}}
                  title={`Fill demo credentials for ${p.role}`} onClick={()=>quickFill(p.role)}>
                  {p.short}
                </button>
              ))}
            </div>
          </div>
        </div>

      </div>
    </div>
  );
};

Object.assign(window, { LoginScreen, LOGIN_PERSONAS });
