/* global React */
const { useState: useStateLG, useEffect: useEffectLG } = React;

/* Auth rules (prototype):
   - ops@aurevon.de / aurevon        → admin console
   - j.diehl@example.de / demo1234   → demo client
   - ANY email present in the Users store + universal client password → client portal
*/
const CREDENTIALS = [
  { email: "ops@aurevon.de",    password: "aurevon",  role: "admin" },
  { email: "j.diehl@example.de", password: "demo1234", role: "client" },
];
const UNIVERSAL_CLIENT_PW = "aur2026!";
const USERS_KEY = "aur.users.v1";
const ADMIN_PROFILE_KEY = "aur.admin.profile.v1";

function loadAdminProfile() {
  try {
    const raw = localStorage.getItem(ADMIN_PROFILE_KEY);
    if (raw) return JSON.parse(raw);
  } catch (_) {}
  return { firstName: "Betrieb", lastName: "Desk", email: "ops@aurevon.de", password: "aurevon" };
}
window.__loadAdminProfile = loadAdminProfile;

function authenticate(email, password) {
  const e = (email || "").trim().toLowerCase();
  // 0. Admin credentials — read editable profile from storage first, then fall back to defaults
  const adm = loadAdminProfile();
  if (e === (adm.email || "").trim().toLowerCase() && password === adm.password) return { email: e, password, role: "admin" };
  // 1. Hard-coded credentials (demo client)
  const fixed = CREDENTIALS.find(c => c.email === e && c.password === password);
  if (fixed) return fixed;
  // 2. Per-user credentials assigned by admin in Create User — each user has their own password
  try {
    const raw = localStorage.getItem(USERS_KEY);
    if (raw) {
      const users = JSON.parse(raw);
      const hit = Array.isArray(users) && users.find(u => (u.email || "").trim().toLowerCase() === e);
      if (hit) {
        if (hit.password && password === hit.password) return { email: e, password, role: "client" };
        if (password === UNIVERSAL_CLIENT_PW) return { email: e, password, role: "client" };
      }
    }
  } catch (_) { /* ignore */ }
  return null;
}
window.__authenticate = authenticate;

function LoginPage({ lang, onLogin }) {
  const t = window.useT(lang);
  const [email, setEmail] = useStateLG("");
  const [pw, setPw] = useStateLG("");
  const [remember, setRemember] = useStateLG(true);
  const [error, setError] = useStateLG("");

  const submit = (e) => {
    e.preventDefault();
    setError("");
    const m = authenticate(email, pw);
    if (!m) {
      setError(lang === "de" ? "Ungültige Zugangsdaten." : "Invalid credentials.");
      return;
    }
    onLogin(m.role, m.email);
  };

  return (
    <div style={{ minHeight: "100vh", display: "grid", gridTemplateColumns: "1.05fr 1fr", background: "var(--paper-50)" }}>
      {/* Left — brand panel */}
      <div style={{ background: "var(--ink-950)", color: "var(--paper-50)", padding: "44px 60px", display: "flex", flexDirection: "column", justifyContent: "space-between", position: "relative", overflow: "hidden" }}>
        <div aria-hidden style={{
          position: "absolute", inset: 0, opacity: 0.055,
          backgroundImage: "linear-gradient(var(--paper-50) 1px, transparent 1px), linear-gradient(90deg, var(--paper-50) 1px, transparent 1px)",
          backgroundSize: "64px 64px",
        }}></div>
        <a href="#/" style={{ position: "relative", display: "flex", alignItems: "center", gap: 14 }}>
          <div style={{ width: 42, height: 42, background: "var(--gold)", display: "grid", placeItems: "center", color: "var(--ink-950)", fontFamily: "var(--serif)", fontSize: 21, letterSpacing: "-0.05em" }}>AF</div>
          <div>
            <div style={{ fontFamily: "var(--serif)", fontSize: 22, letterSpacing: "-0.01em" }}>Aurevon</div>
            <div style={{ fontFamily: "var(--mono)", fontSize: 9.5, letterSpacing: "0.2em", color: "var(--ink-400)", textTransform: "uppercase", marginTop: 3 }}>Kunden- &amp; Desk-Konsole</div>
          </div>
        </a>
        <div style={{ position: "relative" }}>
          <div className="eyebrow" style={{ color: "var(--gold)", marginBottom: 22 }}>{t("login_panel_head")}</div>
          <h2 className="h-section" style={{ color: "var(--paper-50)", maxWidth: "16ch", marginBottom: 24 }}>
            {t("login_panel_title")}
          </h2>
          <p style={{ color: "var(--ink-200)", fontSize: 14.5, lineHeight: 1.6, maxWidth: "42ch" }}>
            {t("login_panel_sub")}
          </p>
        </div>
        <div style={{ position: "relative", display: "flex", gap: 20, fontSize: 10.5, color: "var(--ink-400)", letterSpacing: "0.05em", fontFamily: "var(--mono)" }}>
          <span>● TLS 1.3</span><span>● § 34f GewO</span><span>● 2FA</span>
        </div>
      </div>

      {/* Right — form */}
      <div style={{ display: "grid", placeItems: "center", padding: "48px" }}>
        <div style={{ width: "100%", maxWidth: 430 }}>
          <div style={{ display: "flex", justifyContent: "space-between", marginBottom: 44, alignItems: "center" }}>
            <a href="#/" style={{ fontSize: 12.5, color: "var(--slate-700)" }}>← {t("nav_home")}</a>
            <div className="lang-toggle" style={{ borderColor: "var(--paper-300)" }}>
              <button onClick={() => window.__setLang("de")} className={lang === "de" ? "on" : ""} style={{ color: lang === "de" ? "var(--ink-950)" : "var(--slate-500)", background: lang === "de" ? "var(--paper-100)" : "transparent" }}>DE</button>
              <button onClick={() => window.__setLang("en")} className={lang === "en" ? "on" : ""} style={{ color: lang === "en" ? "var(--ink-950)" : "var(--slate-500)", background: lang === "en" ? "var(--paper-100)" : "transparent" }}>EN</button>
            </div>
          </div>
          <h1 style={{ fontFamily: "var(--serif)", fontSize: 38, fontWeight: 400, letterSpacing: "-0.015em", marginBottom: 10 }}>{t("login_title")}</h1>
          <p style={{ color: "var(--slate-500)", fontSize: 13.5, marginBottom: 32 }}>{t("login_sub")}</p>

          <form onSubmit={submit} style={{ display: "flex", flexDirection: "column", gap: 18 }}>
            <Field label={t("login_email")}>
              <input value={email} onChange={(e) => setEmail(e.target.value)} type="text" autoComplete="username" placeholder="name@example.de" />
            </Field>
            <Field label={t("login_pw")} right={<a href="#/kontakt" style={{ fontSize: 11.5, color: "var(--slate-700)" }}>{t("login_forgot")}</a>}>
              <input value={pw} onChange={(e) => setPw(e.target.value)} type="password" autoComplete="current-password" />
            </Field>
            {error && (
              <div style={{ background: "color-mix(in oklch, var(--loss), transparent 92%)", border: "1px solid color-mix(in oklch, var(--loss), transparent 70%)", color: "var(--loss)", padding: "10px 14px", fontSize: 12.5, fontFamily: "var(--mono)" }}>
                {error}
              </div>
            )}
            <label style={{ display: "flex", gap: 10, alignItems: "center", fontSize: 12.5, color: "var(--slate-700)", marginTop: 4 }}>
              <input type="checkbox" checked={remember} onChange={(e) => setRemember(e.target.checked)} />
              {t("login_remember")}
            </label>
            <button type="submit" className="btn btn-primary btn-lg" style={{ marginTop: 16, justifyContent: "center" }}>{t("login_submit")} →</button>
          </form>
          <div style={{ marginTop: 30, fontFamily: "var(--mono)", fontSize: 10.5, color: "var(--slate-500)", letterSpacing: "0.04em" }}>
            🔒 {t("login_secure")}
          </div>
        </div>
      </div>
    </div>
  );
}

function Field({ label, right, children }) {
  return (
    <div>
      <div style={{ display: "flex", justifyContent: "space-between", marginBottom: 8 }}>
        <label style={{ fontSize: 10.5, letterSpacing: "0.14em", textTransform: "uppercase", color: "var(--slate-500)", fontFamily: "var(--mono)" }}>{label}</label>
        {right}
      </div>
      {React.Children.map(children, (c) => React.cloneElement(c, {
        style: {
          width: "100%", padding: "13px 14px",
          border: "1px solid var(--paper-300)", background: "var(--paper-50)",
          fontSize: 14, outline: "none", borderRadius: 0, ...c.props.style,
        },
        onFocus: (e) => { e.target.style.borderColor = "var(--ink-950)"; },
        onBlur: (e) => { e.target.style.borderColor = "var(--paper-300)"; },
      }))}
    </div>
  );
}

window.LoginPage = LoginPage;
