// hydor-auth.jsx — account-based login gate with NO identities shown.
// Employees sign in with an Account ID (their code) + password. Depends on engine + ui.

function LoginScreen({ onAuthed }) {
  useHydor();
  const [acct, setAcct] = React.useState("");
  const [pw, setPw] = React.useState("");
  const [err, setErr] = React.useState("");
  const [show, setShow] = React.useState(false);
  const [busy, setBusy] = React.useState(false);
  const acctRef = React.useRef();
  const apiOn = !!(window.HYDOR_API_BASE && window.HydorAPI && window.HydorAPI.enabled);
  React.useEffect(() => { if (acctRef.current) acctRef.current.focus(); }, []);

  const submit = async () => {
    if (busy) return;
    if (!acct.trim()) { setErr("Enter your account ID."); return; }
    // When the secure backend is configured, authenticate against it (server enforces roles).
    if (apiOn) {
      setBusy(true); setErr("");
      try {
        const u = await window.HydorAPI.login(acct.trim(), pw);
        // Set role immediately — don't pull state here (it overwrites meta.role)
        // Periodic sync will pull latest state within 30 seconds
        Hydor.setMeta({ role: u.role, currentUserCode: u.code });
        onAuthed(u);
      } catch (e) {
        // if it's a network error, try local fallback
        if (e && e.network) {
          if (Hydor.login(acct.trim(), pw)) {
            onAuthed(Hydor.currentUser());
          } else {
            setErr("Couldn't reach the server. Check your connection.");
          }
        } else {
          setErr(e.message || "Account ID or password is incorrect.");
        }
      } finally { setBusy(false); }
      return;
    }
    // Local engine (offline / pre-backend) fallback — unchanged behaviour.
    if (Hydor.login(acct.trim(), pw)) {
      onAuthed(Hydor.currentUser());
    } else {
      setErr("Account ID or password is incorrect.");
    }
  };

  return (
    <div className="login-stage">
      <div className="login-lang"><LangToggle /></div>
      <div className="login-card">
        <div className="login-brand">
          <div className="side-logo" style={{ width: 42, height: 42 }}>
            <svg viewBox="0 0 24 24" fill="none" stroke="#fff" strokeWidth="2.2" strokeLinecap="round" strokeLinejoin="round" style={{ width: 23, height: 23 }}>
              <path d="M12 2.5C12 2.5 5 9 5 14.5a7 7 0 0014 0C19 9 12 2.5 12 2.5z" />
            </svg>
          </div>
          <div>
            <div className="side-name" style={{ fontSize: 22 }}>HYDOR</div>
            <div className="side-tag">Water Treatment ERP</div>
          </div>
        </div>

        <div className="login-prompt">Sign in</div>

        <div className="field" style={{ marginBottom: 14 }}>
          <label>Account ID</label>
          <input ref={acctRef} className={"inp" + (err ? " err" : "")} value={acct}
            onChange={(e) => { setAcct(e.target.value); setErr(""); }}
            onKeyDown={(e) => e.key === "Enter" && submit()} placeholder="e.g. OM" autoComplete="off" />
        </div>

        <div className="field">
          <label>Password</label>
          <div className="inp-affix">
            <input className={"inp" + (err ? " err" : "")} type={show ? "text" : "password"} value={pw}
              onChange={(e) => { setPw(e.target.value); setErr(""); }}
              onKeyDown={(e) => e.key === "Enter" && submit()} placeholder="Enter password" autoComplete="off" />
            <button className="affix" style={{ pointerEvents: "auto", cursor: "pointer", background: "none", border: "none", color: "var(--text-3)", fontFamily: "var(--font)", fontSize: 11.5 }}
              onClick={() => setShow((x) => !x)} tabIndex={-1}>{show ? "HIDE" : "SHOW"}</button>
          </div>
          {err && <span className="field-hint warn" style={{ marginTop: 6 }}>{err}</span>}
        </div>

        <Btn variant="primary" onClick={submit} className="login-btn" disabled={busy}>
          <Icon name={busy ? "refresh" : "unlock"} size={15} />{busy ? "Signing in…" : "Sign in"}
        </Btn>

        <div className="login-note">
          <Icon name="lock" size={12} />
          <span>Your account ID and password are issued by management. Access is limited to your role — you won't see other people's figures.</span>
        </div>
      </div>
    </div>
  );
}
Object.assign(window, { LoginScreen });
