// Login + Forgot Password page
const { useState } = React;

function GoogleBtn({ onClick, label }) {
  return (
    <button className="btn lg" onClick={onClick}
            style={{ width: "100%", display: "flex", alignItems: "center", justifyContent: "center", gap: 10, background: "#fff" }}>
      <svg width="18" height="18" viewBox="0 0 48 48">
        <path fill="#FFC107" d="M43.6 20.5H42V20H24v8h11.3C33.7 32.9 29.3 36 24 36c-6.6 0-12-5.4-12-12s5.4-12 12-12c3.1 0 5.9 1.2 8 3.1l5.7-5.7C34.5 6.1 29.5 4 24 4 12.9 4 4 12.9 4 24s8.9 20 20 20 20-8.9 20-20c0-1.3-.1-2.3-.4-3.5z"/>
        <path fill="#FF3D00" d="M6.3 14.7l6.6 4.8C14.6 16 18.9 13 24 13c3.1 0 5.9 1.2 8 3.1l5.7-5.7C34.5 7.1 29.5 5 24 5 16.3 5 9.7 9.4 6.3 14.7z"/>
        <path fill="#4CAF50" d="M24 44c5.4 0 10.3-2.1 14-5.4l-6.5-5.3c-2 1.5-4.5 2.7-7.5 2.7-5.3 0-9.7-3.1-11.3-7.5l-6.5 5C9.5 39.5 16.2 44 24 44z"/>
        <path fill="#1976D2" d="M43.6 20.5H42V20H24v8h11.3c-.8 2.3-2.3 4.2-4.3 5.5l6.5 5.3C42 35 44 30 44 24c0-1.3-.1-2.3-.4-3.5z"/>
      </svg>
      {label}
    </button>
  );
}

function LoginApp() {
  const [mode, setMode] = useState("login"); // login | forgot
  const [email, setEmail] = useState("");
  const [password, setPassword] = useState("");
  const [busy, setBusy] = useState(false);
  const [err, setErr] = useState("");
  const [msg, setMsg] = useState("");

  const sb = window.initSupabase && window.initSupabase();

  const onLogin = async (e) => {
    e?.preventDefault();
    if (!sb) return setErr("Supabase not ready");
    setBusy(true); setErr(""); setMsg("");
    const { error } = await sb.auth.signInWithPassword({ email, password });
    setBusy(false);
    if (error) return setErr(error.message);
    window.location.href = "app.html";
  };

  const onGoogle = async () => {
    if (!sb) return;
    await sb.auth.signInWithOAuth({
      provider: "google",
      options: { redirectTo: window.location.origin + "/app.html" }
    });
  };

  const onForgot = async (e) => {
    e?.preventDefault();
    if (!sb) return;
    setBusy(true); setErr(""); setMsg("");
    const { error } = await sb.auth.resetPasswordForEmail(email, {
      redirectTo: window.location.origin + "/reset-password.html"
    });
    setBusy(false);
    if (error) return setErr(error.message);
    setMsg("Check your email for a reset link.");
  };

  return (
    <div className="shell">
      <div className="brand-panel">
        <a className="brand" href="index.html">
          <span className="brand-mark">RL</span>
          Roof Linker
        </a>
        <div className="hd">
          <h1>Welcome back.</h1>
          <p>Sign in to your alliance dashboard.</p>
        </div>
      </div>
      <div className="form-panel">
        <div className="form-body" style={{ flex: 1, maxWidth: 420, margin: "0 auto", paddingTop: 60 }}>
          <h2 className="form-title">{mode === "login" ? "Log in" : "Reset password"}</h2>
          <p className="form-sub">
            {mode === "login"
              ? "Welcome back. Use email + password or Google."
              : "Enter your email and we'll send a reset link."}
          </p>

          {mode === "login" && (
            <>
              <GoogleBtn onClick={onGoogle} label="Continue with Google" />
              <div style={{ textAlign: "center", color: "var(--ink-3)", fontSize: 12, margin: "18px 0" }}>OR</div>
            </>
          )}

          <form onSubmit={mode === "login" ? onLogin : onForgot}>
            <div className="field">
              <label className="field-label">Email</label>
              <input className="input" type="email" autoFocus required
                     value={email} onChange={e => setEmail(e.target.value)} />
            </div>
            {mode === "login" && (
              <div className="field">
                <label className="field-label">Password</label>
                <input className="input" type="password" required
                       value={password} onChange={e => setPassword(e.target.value)} />
              </div>
            )}
            {err && <div style={{ color: "var(--red, #B5302F)", fontSize: 13, marginTop: 8 }}>{err}</div>}
            {msg && <div style={{ color: "var(--green, #4F7A4D)", fontSize: 13, marginTop: 8 }}>{msg}</div>}

            <button className="btn primary lg" disabled={busy} style={{ width: "100%", marginTop: 18 }}>
              {busy ? "Please wait…" : mode === "login" ? "Log in" : "Send reset link"}
            </button>
          </form>

          <div style={{ display: "flex", justifyContent: "space-between", marginTop: 18, fontSize: 13 }}>
            {mode === "login" ? (
              <>
                <a href="#" onClick={(e) => { e.preventDefault(); setMode("forgot"); setErr(""); setMsg(""); }}>Forgot password?</a>
                <a href="signup.html">Create account →</a>
              </>
            ) : (
              <a href="#" onClick={(e) => { e.preventDefault(); setMode("login"); setErr(""); setMsg(""); }}>← Back to login</a>
            )}
          </div>
        </div>
      </div>
    </div>
  );
}

ReactDOM.createRoot(document.getElementById("root")).render(<LoginApp />);
