const LoginPage = ({ onLogin, setPage, redirect, lang }) => {
  const t = (en, id) => lang === "id" ? id : en;
  const [tab,     setTab]     = React.useState("login");
  const [form,    setForm]    = React.useState({ name:"", email:"", password:"", confirm:"" });
  const [error,   setError]   = React.useState("");
  const [loading, setLoading] = React.useState(false);

  const set = (k, v) => { setForm(f => ({ ...f, [k]: v })); setError(""); };

  const handleLogin = async () => {
    if (!form.email || !form.password) { setError(t("Fill in all fields","Isi semua field")); return; }
    setLoading(true);
    try {
      const res  = await fetch("api/login.php", {
        method: "POST", credentials: "include",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ email: form.email, password: form.password })
      });
      const data = await res.json();
      if (!res.ok) { setError(data.error || t("Login failed","Login gagal")); return; }
      if (data.role === "admin") { window.location.href = "admin.html"; return; }
      onLogin(data.user);
      setPage(redirect || "home");
    } catch {
      setError(t("Connection error. Try again.","Gagal terhubung. Coba lagi."));
    } finally { setLoading(false); }
  };

  const handleRegister = async () => {
    if (!form.name || !form.email || !form.password) { setError(t("Fill in all fields","Isi semua field")); return; }
    if (form.password.length < 6) { setError(t("Password min. 6 characters","Password minimal 6 karakter")); return; }
    if (form.password !== form.confirm) { setError(t("Passwords don't match","Password tidak cocok")); return; }
    setLoading(true);
    try {
      const res  = await fetch("api/register.php", {
        method: "POST", credentials: "include",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ name: form.name, email: form.email, password: form.password })
      });
      const data = await res.json();
      if (!res.ok) { setError(data.error || t("Registration failed","Gagal mendaftar")); return; }
      onLogin(data.user);
      setPage(redirect || "home");
    } catch {
      setError(t("Connection error. Try again.","Gagal terhubung. Coba lagi."));
    } finally { setLoading(false); }
  };

  const inputStyle = {
    width:"100%", padding:"12px 14px",
    border:"1px solid #e0deda", background:"#fafaf8",
    fontFamily:"'DM Sans',sans-serif", fontSize:14, color:"#111",
    outline:"none", borderRadius:2
  };
  const tabBtn = (active) => ({
    flex:1, padding:"12px", background:"none",
    border:"none", borderBottom: active ? "2px solid #111" : "2px solid transparent",
    fontFamily:"'DM Sans',sans-serif", fontSize:12, letterSpacing:"0.1em",
    textTransform:"uppercase", fontWeight: active ? 600 : 400,
    color: active ? "#111" : "#aaa", cursor:"pointer"
  });

  return (
    <div style={{ paddingTop:72, minHeight:"100vh", background:"#f9f8f6", display:"flex", alignItems:"center", justifyContent:"center", padding:"120px 24px 60px" }}>
      <div style={{ width:"100%", maxWidth:420 }}>
        <div style={{ textAlign:"center", marginBottom:36 }}>
          <p style={{ fontFamily:"'Cormorant Garant',serif", fontSize:36, fontWeight:300, color:"#111" }}>LOPOBYA</p>
          <p style={{ fontSize:11, letterSpacing:"0.18em", textTransform:"uppercase", color:"#aaa", marginTop:8 }}>
            {redirect === "checkout" ? t("Login to continue checkout","Login untuk melanjutkan checkout") : t("My Account","Akun Saya")}
          </p>
        </div>

        <div style={{ background:"#fff", border:"1px solid #e8e6e2", borderRadius:3 }}>
          <div style={{ display:"flex", borderBottom:"1px solid #e8e6e2" }}>
            <button style={tabBtn(tab==="login")}   onClick={() => { setTab("login");    setError(""); }}>{t("Login","Masuk")}</button>
            <button style={tabBtn(tab==="register")} onClick={() => { setTab("register"); setError(""); }}>{t("Register","Daftar")}</button>
          </div>

          <div style={{ padding:"32px 28px" }}>
            {tab === "register" && (
              <div style={{ marginBottom:16 }}>
                <label style={{ display:"block", fontSize:10, letterSpacing:"0.12em", textTransform:"uppercase", color:"#888", fontWeight:600, marginBottom:6 }}>{t("Full Name","Nama Lengkap")}</label>
                <input style={inputStyle} value={form.name} onChange={e => set("name", e.target.value)} placeholder={t("Your name","Nama kamu")} />
              </div>
            )}

            <div style={{ marginBottom:16 }}>
              <label style={{ display:"block", fontSize:10, letterSpacing:"0.12em", textTransform:"uppercase", color:"#888", fontWeight:600, marginBottom:6 }}>Email</label>
              <input style={inputStyle} type="email" value={form.email} onChange={e => set("email", e.target.value)}
                onKeyDown={e => e.key==="Enter" && tab==="login" && handleLogin()} placeholder="email@example.com" />
            </div>

            <div style={{ marginBottom: tab==="register" ? 16 : 24 }}>
              <label style={{ display:"block", fontSize:10, letterSpacing:"0.12em", textTransform:"uppercase", color:"#888", fontWeight:600, marginBottom:6 }}>Password</label>
              <input style={inputStyle} type="password" value={form.password} onChange={e => set("password", e.target.value)}
                onKeyDown={e => e.key==="Enter" && tab==="login" && handleLogin()}
                placeholder={tab==="register" ? t("Min. 6 characters","Min. 6 karakter") : "••••••••"} />
            </div>

            {tab === "register" && (
              <div style={{ marginBottom:24 }}>
                <label style={{ display:"block", fontSize:10, letterSpacing:"0.12em", textTransform:"uppercase", color:"#888", fontWeight:600, marginBottom:6 }}>{t("Confirm Password","Konfirmasi Password")}</label>
                <input style={inputStyle} type="password" value={form.confirm} onChange={e => set("confirm", e.target.value)}
                  onKeyDown={e => e.key==="Enter" && handleRegister()} placeholder="••••••••" />
              </div>
            )}

            {error && (
              <div style={{ background:"#fff5f5", border:"1px solid #fcc", borderRadius:2, padding:"10px 14px", marginBottom:16 }}>
                <p style={{ fontSize:13, color:"#c55", margin:0 }}>{error}</p>
              </div>
            )}

            <button onClick={tab==="login" ? handleLogin : handleRegister} disabled={loading} style={{
              width:"100%", padding:"14px", background: loading ? "#888" : "#111",
              color:"#f9f8f6", border:"none", cursor: loading ? "not-allowed" : "pointer",
              fontFamily:"'DM Sans',sans-serif", fontSize:11, letterSpacing:"0.16em",
              textTransform:"uppercase", fontWeight:600, borderRadius:2
            }}>
              {loading ? "..." : tab==="login" ? t("Login","Masuk") : t("Create Account","Buat Akun")}
            </button>

            <button onClick={() => setPage("catalog")} style={{
              display:"block", width:"100%", textAlign:"center", marginTop:16,
              background:"none", border:"none", cursor:"pointer", fontSize:12, color:"#aaa", textDecoration:"underline"
            }}>{t("Continue shopping","Lanjut belanja dulu")}</button>
          </div>
        </div>
      </div>
    </div>
  );
};
Object.assign(window, { LoginPage });
