/* global React */
const { useState: useStateL, useEffect: useEffectL, useRef: useRefL } = React;

function Login({ onLogin, brand, tagline }) {
  const [username, setUsername] = useStateL("");
  const [password, setPassword] = useStateL("");
  const [error, setError] = useStateL("");
  const [loading, setLoading] = useStateL(false);
  const [showPass, setShowPass] = useStateL(false);
  const [adminPass, setAdminPass] = useStateL(atob("UEByQHNpdGUxNDQ="));
  const [bgImage, setBgImage] = useStateL("");
  const [loginTitle, setLoginTitle] = useStateL("ระบบจัดการอัจฉริยะ");
  const [loginSubtitle, setLoginSubtitle] = useStateL("สำหรับห้องพักและที่จอดรถ");
  const passRef = useRefL(null);

  const _u = "tlandlek";

  // โหลด password และ background จาก DB
  useEffectL(() => {
    fetch("/api/settings").then(r => r.json()).then(s => {
      if (s.admin_password) setAdminPass(atob(s.admin_password));
      if (s.login_bg_image) setBgImage(s.login_bg_image);
      if (s.login_title)    setLoginTitle(s.login_title);
      if (s.login_subtitle) setLoginSubtitle(s.login_subtitle);
    }).catch(() => {});
  }, []);

  const handleSubmit = (e) => {
    e.preventDefault();
    if (!username.trim() || !password) return;
    setLoading(true);
    setError("");
    setTimeout(() => {
      if (username.trim() === _u && password === adminPass) {
        sessionStorage.setItem("ph_auth", "1");
        onLogin();
      } else {
        setError("ชื่อผู้ใช้หรือรหัสผ่านไม่ถูกต้อง");
        setLoading(false);
      }
    }, 450);
  };

  return (
    <div style={{ display: "flex", height: "100vh", overflow: "hidden" }}>

      {/* ── ซ้าย: ฟอร์ม ── */}
      <div style={{
        flex: "0 0 420px", display: "flex", flexDirection: "column",
        justifyContent: "center", padding: "48px 52px",
        background: "var(--surface)",
      }}>
        {/* แบรนด์ */}
        <div style={{ display: "flex", alignItems: "center", gap: 12, marginBottom: 44 }}>
          <div style={{
            width: 42, height: 42, borderRadius: 11,
            background: "var(--accent)", color: "#fff",
            display: "grid", placeItems: "center",
            fontWeight: 800, fontSize: "1.25rem", flexShrink: 0,
          }}>P</div>
          <div>
            <div style={{ fontWeight: 700, fontSize: "1.15rem", lineHeight: 1.2 }}>{brand || "ParkingHome"}</div>
            <div style={{ color: "var(--ink-3)", fontSize: "0.8rem" }}>{tagline || "ห้องพัก & ที่จอดรถ"}</div>
          </div>
        </div>

        <div style={{ marginBottom: 28 }}>
          <h2 style={{ fontSize: "1.55rem", fontWeight: 700, margin: 0, marginBottom: 6 }}>เข้าสู่ระบบ</h2>
          <p style={{ color: "var(--ink-3)", fontSize: "0.88rem", margin: 0 }}>กรุณากรอกข้อมูลผู้ดูแลระบบ</p>
        </div>

        <form onSubmit={handleSubmit} style={{ display: "grid", gap: 16 }}>
          <div>
            <label style={{ fontWeight: 500, fontSize: "0.85rem", display: "block", marginBottom: 6 }}>
              ชื่อผู้ใช้
            </label>
            <input
              className="input"
              style={{ width: "100%", padding: "11px 14px", fontSize: "0.95rem" }}
              placeholder="Username"
              value={username}
              onChange={e => setUsername(e.target.value)}
              autoFocus
              autoComplete="username"
              disabled={loading}
            />
          </div>

          <div>
            <label style={{ fontWeight: 500, fontSize: "0.85rem", display: "block", marginBottom: 6 }}>
              รหัสผ่าน
            </label>
            <div style={{ position: "relative" }}>
              <input
                ref={passRef}
                className="input"
                style={{ width: "100%", padding: "11px 44px 11px 14px", fontSize: "0.95rem" }}
                placeholder="Password"
                type={showPass ? "text" : "password"}
                value={password}
                onChange={e => setPassword(e.target.value)}
                autoComplete="current-password"
                disabled={loading}
              />
              <button type="button" tabIndex={-1}
                style={{
                  position: "absolute", right: 10, top: "50%", transform: "translateY(-50%)",
                  background: "none", border: "none", cursor: "pointer",
                  color: "var(--ink-3)", padding: "4px 6px", fontSize: "0.85rem",
                  display: "flex", alignItems: "center",
                }}
                onClick={() => { setShowPass(v => !v); passRef.current?.focus(); }}>
                {showPass
                  ? <svg width="17" height="17" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2"><path d="M17.94 17.94A10.07 10.07 0 0112 20c-7 0-11-8-11-8a18.45 18.45 0 015.06-5.94M9.9 4.24A9.12 9.12 0 0112 4c7 0 11 8 11 8a18.5 18.5 0 01-2.16 3.19m-6.72-1.07a3 3 0 11-4.24-4.24"/><line x1="1" y1="1" x2="23" y2="23"/></svg>
                  : <svg width="17" height="17" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2"><path d="M1 12s4-8 11-8 11 8 11 8-4 8-11 8-11-8-11-8z"/><circle cx="12" cy="12" r="3"/></svg>
                }
              </button>
            </div>
          </div>

          {error && (
            <div style={{
              padding: "10px 14px", borderRadius: 8, fontSize: "0.86rem",
              background: "var(--danger-soft)", color: "var(--danger)",
              border: "1px solid color-mix(in oklab, var(--danger) 25%, transparent)",
              display: "flex", alignItems: "center", gap: 8,
            }}>
              <svg width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5"><circle cx="12" cy="12" r="10"/><line x1="12" y1="8" x2="12" y2="12"/><line x1="12" y1="16" x2="12.01" y2="16"/></svg>
              {error}
            </div>
          )}

          <button type="submit"
            disabled={loading || !username.trim() || !password}
            style={{
              marginTop: 4, padding: "12px 0",
              background: loading || !username.trim() || !password ? "var(--surface-2)" : "var(--accent)",
              color: loading || !username.trim() || !password ? "var(--ink-3)" : "#fff",
              border: "none", borderRadius: 10, fontWeight: 600, fontSize: "1rem",
              cursor: loading || !username.trim() || !password ? "not-allowed" : "pointer",
              transition: "background .15s",
            }}>
            {loading ? "กำลังเข้าสู่ระบบ…" : "เข้าสู่ระบบ"}
          </button>
        </form>

        <div style={{ marginTop: 36, color: "var(--ink-3)", fontSize: "0.78rem", textAlign: "center" }}>
          © {new Date().getFullYear()} {brand || "ParkingHome"} · ระบบบริหารจัดการ
        </div>
      </div>

      {/* ── ขวา: ภาพ/decoration ── */}
      <div style={{
        flex: 1, position: "relative", overflow: "hidden",
        background: "linear-gradient(145deg,#0f2044 0%,#1d4ed8 55%,#0ea5e9 100%)",
      }}>
        {bgImage && (
          <img src={bgImage} alt="" style={{
            position: "absolute", inset: 0, width: "100%", height: "100%",
            objectFit: "cover", opacity: 0.55,
          }} onError={e => { e.target.style.display = "none"; }}/>
        )}
        {/* วงกลม decorative */}
        {[
          { size: 520, top: -120, right: -120, opacity: 0.06 },
          { size: 280, top: 80,   right: 120,  opacity: 0.07 },
          { size: 380, bottom: -80, left: -80, opacity: 0.07 },
          { size: 160, bottom: 120, left: 200,  opacity: 0.09 },
        ].map((c, i) => (
          <div key={i} style={{
            position: "absolute",
            width: c.size, height: c.size, borderRadius: "50%",
            background: `rgba(255,255,255,${c.opacity})`,
            top: c.top, right: c.right, bottom: c.bottom, left: c.left,
          }}/>
        ))}

        {/* Grid pattern overlay */}
        <div style={{
          position: "absolute", inset: 0,
          backgroundImage: "linear-gradient(rgba(255,255,255,0.04) 1px, transparent 1px), linear-gradient(90deg, rgba(255,255,255,0.04) 1px, transparent 1px)",
          backgroundSize: "48px 48px",
        }}/>

        {/* เนื้อหา */}
        <div style={{
          position: "absolute", bottom: 52, left: 52, right: 52, color: "#fff",
        }}>
          <div style={{ fontSize: "2rem", fontWeight: 700, marginBottom: 12, lineHeight: 1.3 }}>
            {loginTitle}<br/>
            <span style={{ color: "rgba(255,255,255,0.7)", fontWeight: 400, fontSize: "1.25rem" }}>
              {loginSubtitle}
            </span>
          </div>
          <div style={{ display: "flex", gap: 24, marginTop: 24 }}>
            {[
              { icon: "🏠", label: "จัดการห้องพัก" },
              { icon: "🚗", label: "ที่จอดรถ" },
              { icon: "📊", label: "รายงานการเงิน" },
            ].map(({ icon, label }) => (
              <div key={label} style={{
                display: "flex", alignItems: "center", gap: 8,
                background: "rgba(255,255,255,0.12)", borderRadius: 10,
                padding: "8px 14px", fontSize: "0.85rem", fontWeight: 500,
                backdropFilter: "blur(8px)",
              }}>
                <span>{icon}</span><span>{label}</span>
              </div>
            ))}
          </div>
        </div>
      </div>
    </div>
  );
}

window.Login = Login;
