const { useState } = React;

function LoginPage({ onLogin }) {
  const [username, setUsername] = useState("");
  const [password, setPassword] = useState("");
  const [error, setError] = useState("");
  const [loading, setLoading] = useState(false);

  const handleSubmit = async (e) => {
    e.preventDefault();
    setError("");
    setLoading(true);
    try {
      const res = await fetch("/api/login", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ username, password })
      });
      const data = await res.json();
      if (!res.ok) {
        setError(data.error || "Login failed");
        setLoading(false);
        return;
      }
      localStorage.setItem("auth_token", data.token);
      localStorage.setItem("auth_user", JSON.stringify(data.user));
      onLogin(data.user);
    } catch (err) {
      setError("Network error. Please try again.");
    }
    setLoading(false);
  };

  return (
    <div style={{
      minHeight: "100vh", background: "#0F172A",
      display: "flex", alignItems: "center", justifyContent: "center",
      fontFamily: "'Inter', -apple-system, sans-serif"
    }}>
      <div style={{
        width: 400, background: "#1E293B", borderRadius: 16,
        padding: "48px 40px", boxShadow: "0 25px 50px rgba(0,0,0,0.4)"
      }}>
        {/* Logo */}
        <div style={{ textAlign: "center", marginBottom: 32 }}>
          <img src="neurachain.png" alt="NeuraChain" style={{ height: 48, borderRadius: 8, marginBottom: 12 }} />
          <h1 style={{ fontSize: 24, fontWeight: 800, color: "white", margin: 0, letterSpacing: "-0.02em" }}>
            NeuraChain
          </h1>
          <p style={{ fontSize: 13, color: "#94A3B8", marginTop: 4 }}>
            AI Manufacturing Solutions
          </p>
        </div>

        <form onSubmit={handleSubmit}>
          <div style={{ marginBottom: 16 }}>
            <label style={{ display: "block", fontSize: 13, fontWeight: 600, color: "#CBD5E1", marginBottom: 6 }}>
              Username
            </label>
            <input
              type="text"
              value={username}
              onChange={e => setUsername(e.target.value)}
              placeholder="Enter username"
              required
              style={{
                width: "100%", padding: "10px 14px", borderRadius: 8,
                border: "1px solid #334155", background: "#0F172A", color: "white",
                fontSize: 14, outline: "none", boxSizing: "border-box"
              }}
              onFocus={e => e.target.style.borderColor = "#3B82F6"}
              onBlur={e => e.target.style.borderColor = "#334155"}
            />
          </div>

          <div style={{ marginBottom: 24 }}>
            <label style={{ display: "block", fontSize: 13, fontWeight: 600, color: "#CBD5E1", marginBottom: 6 }}>
              Password
            </label>
            <input
              type="password"
              value={password}
              onChange={e => setPassword(e.target.value)}
              placeholder="Enter password"
              required
              style={{
                width: "100%", padding: "10px 14px", borderRadius: 8,
                border: "1px solid #334155", background: "#0F172A", color: "white",
                fontSize: 14, outline: "none", boxSizing: "border-box"
              }}
              onFocus={e => e.target.style.borderColor = "#3B82F6"}
              onBlur={e => e.target.style.borderColor = "#334155"}
            />
          </div>

          {error && (
            <div style={{
              background: "#7F1D1D", color: "#FCA5A5", padding: "10px 14px",
              borderRadius: 8, fontSize: 13, marginBottom: 16, border: "1px solid #991B1B"
            }}>
              {error}
            </div>
          )}

          <button
            type="submit"
            disabled={loading}
            style={{
              width: "100%", padding: "12px", borderRadius: 8, border: "none",
              background: loading ? "#1E40AF" : "#3B82F6", color: "white",
              fontSize: 14, fontWeight: 700, cursor: loading ? "not-allowed" : "pointer",
              transition: "background 0.15s"
            }}
            onMouseOver={e => { if (!loading) e.currentTarget.style.background = "#2563EB"; }}
            onMouseOut={e => { if (!loading) e.currentTarget.style.background = "#3B82F6"; }}
          >
            {loading ? "Signing in..." : "Sign In"}
          </button>
        </form>

        <div style={{ marginTop: 32, borderTop: "1px solid #334155", paddingTop: 20 }}>
          <p style={{ fontSize: 12, color: "#64748B", textAlign: "center", marginBottom: 12 }}>
            Demo Account
          </p>
          <div style={{ display: "flex", gap: 8, justifyContent: "center", flexWrap: "wrap" }}>
            <button
              onClick={() => { setUsername("demo"); setPassword("demo123"); }}
              style={{
                background: "#0F172A", border: "1px solid #334155", borderRadius: 6,
                padding: "6px 12px", color: "#94A3B8", fontSize: 11, cursor: "pointer",
                fontWeight: 600
              }}
              onMouseOver={e => e.currentTarget.style.borderColor = "#3B82F6"}
              onMouseOut={e => e.currentTarget.style.borderColor = "#334155"}
            >
              Demo: demo/demo123
            </button>
          </div>
        </div>
      </div>
    </div>
  );
}

window.LoginPage = LoginPage;
