// Login page + session helpers
const SESSION_KEY = "erpvision.session";
function getSession() {
  try { return JSON.parse(localStorage.getItem(SESSION_KEY)); } catch (e) { return null; }
}
function setSession(s) { localStorage.setItem(SESSION_KEY, JSON.stringify(s)); }
function clearSession() { localStorage.removeItem(SESSION_KEY); }

// Language has to be reachable before sign-in, so the login card carries its
// own inline switcher rather than relying on the topbar one.
function LoginLangBar() {
  const lang = useLang();
  const langs = I18N.list();
  if (langs.length < 2) return null;
  return (
    <div className="login-langs">
      {langs.map((l) => (
        <button key={l.code} type="button" className={"login-lang" + (l.code === lang ? " on" : "")}
          onClick={() => I18N.setLang(l.code)}>{l.label}</button>
      ))}
    </div>
  );
}

// Sign-in takes an email or a username. Email goes to the central service,
// which resolves the tenant; a username can only be checked by the company's
// own backend, so it needs a tenant pinned by the shared link (?d=test1). That
// is the path for employees, who often have no email address at all.
function Login({ onLogin }) {
  const { useState } = React;
  const [id, setId] = useState("");
  const [pw, setPw] = useState("");
  const [err, setErr] = useState("");
  const [busy, setBusy] = useState(false);
  const tenant = API.tenantDomain();

  const submit = async (e) => {
    e.preventDefault();
    // Emails and usernames are case-insensitive — sign in on the lowercased value.
    const v = id.trim().toLowerCase();
    if (!v) { setErr(T(tenant ? "login.errIdentifier" : "login.errEmail")); return; }
    if (!pw) { setErr(T("login.errPassword")); return; }
    setBusy(true);
    try {
      const isEmail = v.indexOf("@") !== -1;
      const d = isEmail ? await API.login(v, pw) : await API.loginUser(v, pw);
      const u = d.user || {};
      const name = [u.first_name, u.last_name].filter(Boolean).join(" ") || u.username || v;
      let live = { kind: "admin", name, email: u.email || (isEmail ? v : ""), role: u.is_superuser ? "Owner" : "Administrator", api: true };
      // Portal-only roles land in the standalone ESS shell; owners/admins/managers
      // keep the full ERP (with My Portal embedded as a tab).
      if (!u.is_superuser && u.role !== "admin" && u.role !== "manager") {
        try {
          const emp = await API.hr.me(); // linked employee record → ESS portal
          live = { kind: "employee", name: emp.name, email: live.email, empId: emp.id, api: true };
        } catch (ignored) {}
      }
      setSession(live);
      onLogin(live);
    } catch (ex) {
      if (ex.code === "no-tenant") setErr(T("login.errNoCompany"));
      else setErr(ex.status ? String(ex.message) : T("login.errNoAccount"));
    } finally {
      setBusy(false);
    }
  };
  return (
    <div className="login-wrap" data-screen-label="Login">
      <div className="login-card">
        <div className="logo login-logo">
          <span className="logo-mark"></span>
          <span className="logo-word display">{T("app.brand")}</span>
          <span className="logo-tag">{T("app.brandTag")}</span>
        </div>
        <h1 className="display login-title">{T("login.title")}</h1>
        <p className="login-sub">{tenant ? T("login.company", { domain: tenant }) : T("login.subtitle")}</p>
        <form onSubmit={submit}>
          {/* type="text" once usernames are allowed — type="email" would make the
              browser reject them before submit ever runs. */}
          <Field label={T(tenant ? "login.identifier" : "login.email")}>
            <Input type={tenant ? "text" : "email"} value={id} autoFocus
              placeholder={T(tenant ? "login.identifierPlaceholder" : "login.emailPlaceholder")}
              onChange={(e) => { setId(e.target.value.toLowerCase()); setErr(""); }} />
          </Field>
          <Field label={T("login.password")} error={err}>
            <Input type="password" placeholder="••••••••" value={pw}
              onChange={(e) => { setPw(e.target.value); setErr(""); }} />
          </Field>
          <Btn variant="primary" type="submit" disabled={busy} style={{ width: "100%", justifyContent: "center" }}>{busy ? T("login.signingIn") : T("login.title")}</Btn>
        </form>
        <LoginLangBar />
      </div>
    </div>
  );
}
Object.assign(window, { Login, getSession, setSession, clearSession });
