/* global React */
const { useState: useStateLogin, useEffect: useEffectLogin } = React;

// 9 nhóm đăng nhập · phân quyền theo bộ phận
// scope: mảng mã dễpt của quy trình được xem; "ALL" = xem toàn bộ
const KLG_COMPANIES = [
  { id: "kd",   name: "Bộ phận Kinh Doanh",            scope: ["KD"] },
  { id: "dv",   name: "Bộ phận Dịch Vụ",              scope: ["DV"] },
  { id: "mkt",  name: "Bộ phận Marketing",              scope: ["MKT"] },
  { id: "cr",   name: "Bộ phận Customer Relations",    scope: ["CR"] },
  { id: "hcns", name: "Bộ phận Hành Chính Nhân Sự",      scope: ["HCNS"] },
  { id: "tckt", name: "Bộ phận Tài Chính Kế Toán",       scope: ["TCKT"] },
  { id: "it",   name: "Bộ phận Công Nghệ Thông Tin",     scope: ["IT"] },
  { id: "qt",   name: "Ban Quản Trị",                    scope: "ALL" },
  { id: "tgd",  name: "Nhóm Tổng Giám Đốc",             scope: "ALL" }
];

// DEMO — quản trị viên thay bằng mật khẩu thật, đổi mỗi tháng
// Mật khẩu thử nghiệm: "kimlien" cho mọi đơn vị
const KLG_PASSWORDS = Object.fromEntries(KLG_COMPANIES.map((c) => [c.id, "kimlien"]));

const AUTH_KEY = "klg_auth";
const AUTH_TTL_MS = 30 * 24 * 60 * 60 * 1000; // 30 ngày

function readAuth() {
  try {
    const raw = localStorage.getItem(AUTH_KEY);
    if (!raw) return null;
    const t = JSON.parse(raw);
    if (!t.ts || Date.now() - t.ts > AUTH_TTL_MS) {
      localStorage.removeItem(AUTH_KEY);
      return null;
    }
    return t;
  } catch { return null; }
}

function LoginScreen({ onSuccess }) {
  const [company, setCompany] = useStateLogin(KLG_COMPANIES[0].id);
  const [password, setPassword] = useStateLogin("");
  const [error, setError] = useStateLogin("");
  const [shake, setShake] = useStateLogin(false);

  const submit = (e) => {
    e.preventDefault();
    setError("");
    fetch("/api/auth/login", {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify({ company, password })
    })
    .then(async (res) => {
      const data = await res.json();
      if (!res.ok) {
        throw new Error(data.error || "Mật khẩu không đúng. Vui lòng kiểm tra lại.");
      }
      return data;
    })
    .then((data) => {
      const token = { company: data.user.id, name: data.user.name, scope: data.user.scope, ts: Date.now() };
      localStorage.setItem("klg_token", data.token);
      localStorage.setItem(AUTH_KEY, JSON.stringify(token));
      onSuccess(token);
    })
    .catch((err) => {
      setError(err.message);
      setShake(true);
      setTimeout(() => setShake(false), 400);
    });
  };

  const selectedCompany = KLG_COMPANIES.find((c) => c.id === company);

  return (
    <div className="klg-login-root" style={loginStyles.root}>
      {/* Brand panel */}
      <aside className="klg-login-brand" style={loginStyles.brandPanel}>
        <div style={loginStyles.watermarkBg}>
          <img
            src={window.__resources?.logoMarkWhite || "assets/kimlien-logo-mark-white.png"}
            alt=""
            style={{ width: 720, height: 720, opacity: 0.05 }}
          />
        </div>

        <header style={loginStyles.brandHeader}>
          <img
            src={window.__resources?.logoMark || "assets/kimlien-logo-mark.png"}
            alt=""
            style={{ width: 44, height: 44 }}
          />
          <div>
            <div style={loginStyles.wordmark}>KIMLIEN GROUP</div>
            <div style={loginStyles.wordmarkSub}>HỆ THỐNG QUY TRÌNH NỘI BỘ</div>
          </div>
        </header>

        <div style={loginStyles.brandBody}>
          <div style={loginStyles.eyebrowGold}>TÀI LIỆU NỘI BỘ · KHÔNG PHỔ BIẾN</div>
          <h1 style={loginStyles.headline}>
            Vui lòng<br/>
            <em style={loginStyles.headlineEm}>xác thực truy cập.</em>
          </h1>
          <p style={loginStyles.lede}>
            Hệ thống lưu trữ toàn bộ quy trình vận hành của Tập đoàn Kim Liên.
            Mỗi công ty trực thuộc được cấp một tài khoản riêng; mật khẩu được
            cập nhật định kỳ hàng tháng bởi Văn phòng Quản trị Hệ thống.
          </p>
        </div>

        <footer style={loginStyles.brandFooter}>
          <span><b>9</b> bộ phận / nhóm</span>
          <span style={loginStyles.metaDot} />
          <span>Cập nhật <b>04.05.2026</b></span>
        </footer>
      </aside>

      {/* Login form */}
      <main className="klg-login-form" style={loginStyles.formPanel}>
        <form
          onSubmit={submit}
          style={{
            ...loginStyles.form,
            transform: shake ? "translateX(0)" : "translateX(0)",
            animation: shake ? "klg-shake 0.4s" : "none",
          }}
        >
          <div style={loginStyles.eyebrow}>ĐĂNG NHẬP</div>
          <h2 style={loginStyles.formTitle}>Vào hệ thống</h2>
          <p style={loginStyles.formLede}>
            Chọn bộ phận của bạn và nhập mật khẩu được cấp.
          </p>

          <div style={loginStyles.field}>
            <label style={loginStyles.label} htmlFor="login-company">Bộ phận / nhóm</label>
            <select
              id="login-company"
              value={company}
              onChange={(e) => { setCompany(e.target.value); setError(""); }}
              style={loginStyles.select}
            >
              {KLG_COMPANIES.map((c) => (
                <option key={c.id} value={c.id}>{c.name}</option>
              ))}
            </select>
          </div>

          <div style={loginStyles.field}>
            <label style={loginStyles.label} htmlFor="login-password">Mật khẩu</label>
            <input
              id="login-password"
              type="password"
              value={password}
              onChange={(e) => { setPassword(e.target.value); setError(""); }}
              placeholder="Nhập mật khẩu được cấp"
              autoComplete="current-password"
              autoFocus
              style={{
                ...loginStyles.input,
                borderColor: error ? "var(--kl-burgundy, #8a2c2c)" : "var(--line-2)",
              }}
            />
            {error && <div style={loginStyles.errorMsg}>{error}</div>}
          </div>

          <button type="submit" style={loginStyles.submitBtn}>
            <span style={{ whiteSpace: "nowrap" }}>Vào hệ thống</span>
            <span style={loginStyles.arrow}>→</span>
          </button>



          <div style={loginStyles.formFooter}>
            Mật khẩu được cấp định kỳ. Nếu bạn không có hoặc đã quên mật khẩu,
            vui lòng liên hệ <b>Quản trị Hệ thống</b> qua kênh nội bộ.
          </div>
        </form>
      </main>

      <style>{`
        @keyframes klg-shake {
          0%, 100% { transform: translateX(0); }
          20% { transform: translateX(-6px); }
          40% { transform: translateX(6px); }
          60% { transform: translateX(-4px); }
          80% { transform: translateX(4px); }
        }
        @media (max-width: 880px) {
          .klg-login-root { grid-template-columns: 1fr !important; }
          .klg-login-brand { min-height: 280px !important; padding: 32px !important; }
          .klg-login-form { padding: 40px 24px !important; }
        }
      `}</style>
    </div>
  );
}

function AuthGate({ children }) {
  const [auth, setAuth] = useStateLogin(() => readAuth());

  // Set globals SYNCHRONOUSLY during render so children see them on first render
  window.__klg_auth = auth;
  window.__klg_company = auth ? KLG_COMPANIES.find((c) => c.id === auth.company) : null;
  window.__klg_logout = () => {
    localStorage.removeItem(AUTH_KEY);
    localStorage.removeItem("klg_token");
    setAuth(null);
  };

  if (!auth) return <LoginScreen onSuccess={setAuth} />;
  return children;
}

const loginStyles = {
  root: {
    minHeight: "100vh",
    display: "grid",
    gridTemplateColumns: "minmax(420px, 1.1fr) minmax(420px, 1fr)",
    background: "#fff",
    fontFamily: "var(--font-body)",
  },
  brandPanel: {
    position: "relative",
    background: "var(--kl-bg-blue)",
    color: "var(--fg-on-dark)",
    padding: "40px 56px",
    display: "flex",
    flexDirection: "column",
    overflow: "hidden",
  },
  watermarkBg: {
    position: "absolute",
    inset: 0,
    display: "flex",
    alignItems: "center",
    justifyContent: "center",
    pointerEvents: "none",
  },
  brandHeader: {
    position: "relative",
    display: "flex",
    alignItems: "center",
    gap: 14,
  },
  wordmark: {
    fontFamily: "var(--font-display)",
    fontSize: 18,
    whiteSpace: "nowrap",
    letterSpacing: "0.18em",
    color: "var(--kl-gold)",
  },
  wordmarkSub: {
    fontFamily: "var(--font-accent)",
    fontSize: 10,
    letterSpacing: "0.14em",
    color: "var(--fg-on-dark-2)",
    marginTop: 4,
  },
  brandBody: {
    position: "relative",
    margin: "auto 0",
    paddingTop: 40,
  },
  eyebrowGold: {
    fontFamily: "var(--font-accent)",
    fontSize: 11,
    letterSpacing: "0.18em",
    color: "var(--kl-gold)",
    marginBottom: 24,
  },
  headline: {
    fontFamily: "var(--font-display)",
    fontSize: "clamp(36px, 4.4vw, 56px)",
    lineHeight: 1.05,
    color: "var(--fg-on-dark)",
    fontWeight: 400,
    margin: 0,
    letterSpacing: "-0.015em",
  },
  headlineEm: {
    fontStyle: "italic",
    color: "var(--kl-gold)",
  },
  lede: {
    fontFamily: "var(--font-display)",
    fontStyle: "italic",
    fontSize: 16,
    lineHeight: 1.6,
    color: "var(--fg-on-dark-2)",
    marginTop: 28,
    maxWidth: 480,
    borderLeft: "2px solid var(--kl-gold)",
    paddingLeft: 20,
  },
  brandFooter: {
    position: "relative",
    paddingTop: 20,
    borderTop: "1px solid var(--line-on-dark-gold)",
    display: "flex",
    gap: 14,
    alignItems: "center",
    color: "var(--fg-on-dark-2)",
    fontSize: 12,
    fontFamily: "var(--font-accent)",
    letterSpacing: "0.04em",
  },
  metaDot: {
    width: 4, height: 4,
    background: "var(--kl-gold)",
    borderRadius: "50%",
  },

  formPanel: {
    display: "flex",
    alignItems: "center",
    justifyContent: "center",
    padding: "56px 64px",
    background: "#fff",
  },
  form: {
    width: "100%",
    maxWidth: 420,
  },
  eyebrow: {
    fontFamily: "var(--font-accent)",
    fontSize: 11,
    letterSpacing: "0.18em",
    color: "var(--kl-gold-deep)",
    marginBottom: 16,
  },
  formTitle: {
    fontFamily: "var(--font-display)",
    fontSize: 36,
    color: "var(--kl-black)",
    fontWeight: 400,
    margin: 0,
    lineHeight: 1.1,
    letterSpacing: "-0.01em",
  },
  formLede: {
    fontSize: 14,
    lineHeight: 1.55,
    color: "var(--fg-3)",
    margin: "12px 0 32px",
  },
  field: {
    marginBottom: 18,
  },
  label: {
    display: "block",
    fontFamily: "var(--font-accent)",
    fontSize: 11,
    letterSpacing: "0.12em",
    textTransform: "uppercase",
    color: "var(--fg-3)",
    marginBottom: 8,
  },
  select: {
    width: "100%",
    padding: "11px 14px",
    border: "1px solid var(--line-2)",
    borderRadius: 0,
    background: "#fff",
    fontFamily: "var(--font-body)",
    fontSize: 14,
    color: "var(--fg-1)",
    outline: "none",
    cursor: "pointer",
    appearance: "none",
    backgroundImage:
      "url(\"data:image/svg+xml;utf8,<svg xmlns='http://www.w3.org/2000/svg' width='10' height='6' viewBox='0 0 10 6'><path d='M1 1l4 4 4-4' stroke='%23808080' stroke-width='1.5' fill='none' stroke-linecap='round' stroke-linejoin='round'/></svg>\")",
    backgroundRepeat: "no-repeat",
    backgroundPosition: "right 14px center",
    paddingRight: 36,
  },
  input: {
    width: "100%",
    padding: "11px 14px",
    border: "1px solid var(--line-2)",
    borderRadius: 0,
    background: "#fff",
    fontFamily: "var(--font-body)",
    fontSize: 14,
    color: "var(--fg-1)",
    outline: "none",
    transition: "border-color 150ms ease",
  },
  errorMsg: {
    marginTop: 8,
    fontSize: 12,
    color: "#8a2c2c",
    fontFamily: "var(--font-accent)",
    letterSpacing: "0.02em",
  },
  submitBtn: {
    width: "100%",
    padding: "14px 18px",
    background: "var(--kl-bg-blue)",
    color: "var(--fg-on-dark)",
    border: "none",
    cursor: "pointer",
    fontFamily: "var(--font-accent)",
    fontSize: 13,
    letterSpacing: "0.12em",
    textTransform: "uppercase",
    display: "flex",
    alignItems: "center",
    justifyContent: "center",
    gap: 12,
    marginTop: 8,
    transition: "background 150ms ease",
  },
  arrow: {
    fontFamily: "var(--font-display)",
    fontSize: 18,
    color: "var(--kl-gold)",
  },
  demoNote: {
    marginTop: 20,
    padding: "12px 14px",
    border: "1px dashed var(--line-2)",
    background: "var(--kl-platinum)",
    fontSize: 11,
    lineHeight: 1.5,
    color: "var(--fg-3)",
    fontFamily: "var(--font-accent)",
  },
  demoLabel: {
    display: "inline-block",
    background: "var(--kl-gold)",
    color: "var(--kl-black)",
    fontWeight: 600,
    fontSize: 9,
    letterSpacing: "0.1em",
    padding: "2px 6px",
    marginRight: 8,
  },
  code: {
    fontFamily: "ui-monospace, SF Mono, Menlo, monospace",
    fontSize: 11,
    background: "#fff",
    border: "1px solid var(--line-1)",
    padding: "1px 5px",
    color: "var(--kl-black)",
  },
  formFooter: {
    marginTop: 24,
    paddingTop: 16,
    borderTop: "1px solid var(--line-1)",
    fontSize: 12,
    lineHeight: 1.6,
    color: "var(--fg-3)",
  },
};

// Apply responsive class names
loginStyles.root = { ...loginStyles.root };

window.LoginScreen = LoginScreen;
window.AuthGate = AuthGate;
window.KLG_COMPANIES = KLG_COMPANIES;
