/* ============================================================
   login.jsx — production sign-in + self-serve signup (mail-free).
   One universal login: email + password or Google. The account's role
   decides the app after sign-in (no persona picker). New companies
   self-register (company + GSTIN + owner) and are signed straight in as
   the finance owner. Demo logins are tucked into a dev-only panel.
   ============================================================ */

// "Sign in with Google" — renders via Google Identity Services once its script
// (loaded async in index.html) is ready; hands back a signed ID token.
function GoogleButton({ clientId, onCredential }) {
  const ref = React.useRef(null);
  const [busy, setBusy] = React.useState(false);
  const [err, setErr] = React.useState("");
  const desktop = !!(window.isDesktopApp && window.isDesktopApp());
  React.useEffect(() => {
    // WEB only: render Google's GIS button. Desktop uses the native flow below (GIS can't
    // run in the webview), so the effect no-ops there.
    if (desktop || !clientId || !ref.current) return;
    let tries = 0;
    const t = setInterval(() => {
      const g = window.google && window.google.accounts && window.google.accounts.id;
      if (g) {
        clearInterval(t);
        window.google.accounts.id.initialize({
          client_id: clientId,
          callback: (resp) => onCredential(resp.credential),
        });
        window.google.accounts.id.renderButton(ref.current, {
          theme: "outline", size: "large", width: 300, text: "continue_with",
        });
      } else if (++tries > 60) {
        clearInterval(t);
      }
    }, 100);
    return () => clearInterval(t);
  }, [clientId, desktop]);

  if (desktop) {
    // DESKTOP: open the system browser (native loopback + PKCE) → id_token → login
    return (
      <div style={{ display: "flex", flexDirection: "column", alignItems: "center", gap: 6 }}>
        <button className="btn btn-lg" style={{ width: 300, justifyContent: "center" }} disabled={busy}
          onClick={async () => {
            setErr(""); setBusy(true);
            try {
              const tok = await window.desktopGoogleOAuth("openid email profile");
              await onCredential(tok.id_token);
            } catch (e) { setErr((e && e.message) || "Google sign-in failed."); }
            finally { setBusy(false); }
          }}>
          {busy ? "Opening your browser…" : "Continue with Google"}
        </button>
        {err && <div className="tiny" style={{ color: "#c0392b" }}>{err}</div>}
      </div>
    );
  }
  return <div ref={ref} style={{ display: "flex", justifyContent: "center" }} />;
}

function Field({ label, hint, ...props }) {
  return (
    <div style={{ marginTop: 12 }}>
      <div className="field-label">{label}</div>
      <input className="input" style={{ width: "100%" }} {...props} />
      {hint && <div className="tiny" style={{ marginTop: 4 }}>{hint}</div>}
    </div>
  );
}

// --- sign-in form ---------------------------------------------------------
function SignInForm({ onLogin, err, setErr }) {
  const [email, setEmail] = React.useState("");
  const [password, setPassword] = React.useState("");
  const [busy, setBusy] = React.useState(false);

  const submit = async (e) => {
    if (e) e.preventDefault();
    setErr(""); setBusy(true);
    try {
      await onLogin(email.trim(), password);
    } catch (ex) {
      setErr(ex && ex.status === 429
        ? "Too many attempts — try again in a few minutes."
        : "Invalid email or password.");
    } finally { setBusy(false); }
  };

  return (
    <form onSubmit={submit}>
      <Field label="Email" type="email" autoFocus value={email}
        onChange={(e) => setEmail(e.target.value)} placeholder="you@company.in" />
      <Field label="Password" type="password" value={password}
        onChange={(e) => setPassword(e.target.value)} placeholder="••••••••" />
      {err && <div className="hint" style={{ marginTop: 14 }}><Ic.x style={{ marginTop: 1, flex: "0 0 14px" }} /><div>{err}</div></div>}
      <button className="btn btn-primary btn-lg" type="submit" disabled={busy}
        style={{ width: "100%", justifyContent: "center", marginTop: 16 }}>
        {busy ? "Signing in…" : "Sign in"}
      </button>
      <div className="tiny" style={{ marginTop: 12, textAlign: "center", color: "var(--text-3)" }}>
        Forgot your password? Ask your organisation owner (or Lekha admin) to reset it.
      </div>
    </form>
  );
}

// --- self-serve signup form ----------------------------------------------
function SignUpForm({ onSignup, err, setErr }) {
  const [f, setF] = React.useState({ company_name: "", name: "", email: "", password: "", confirm: "" });
  const [busy, setBusy] = React.useState(false);
  const set = (k) => (e) => setF({ ...f, [k]: e.target.value });

  // Client-side validation (mirrors the server): button stays disabled until valid.
  const cn = f.company_name.trim();
  const nameOk = cn.length >= 2 && cn.length <= 120;
  const emailOk = /^\S+@\S+\.\S+$/.test(f.email.trim());
  const ownerOk = f.name.trim().length > 0;
  const pwOk = f.password.length >= 10;
  const matchOk = f.confirm.length > 0 && f.password === f.confirm;
  const valid = nameOk && emailOk && ownerOk && pwOk && matchOk;

  const submit = async (e) => {
    if (e) e.preventDefault();
    if (!valid || busy) return;
    setErr(""); setBusy(true);
    try {
      await onSignup({
        company_name: cn,
        name: f.name.trim(), email: f.email.trim(), password: f.password,
      });
      // success → the auth hook signs the owner in; the app re-renders.
    } catch (ex) {
      setErr((ex && ex.message) || "Could not create your account.");
    } finally { setBusy(false); }
  };

  return (
    <form onSubmit={submit}>
      <Field label="Company name" autoFocus value={f.company_name}
        onChange={set("company_name")} placeholder="Acme Foods Pvt Ltd"
        hint="Enter it exactly as it appears in Tally — Lekha matches on this name." />
      <Field label="Your name" value={f.name} onChange={set("name")} placeholder="Sam Owner" />
      <Field label="Work email" type="email" value={f.email}
        onChange={set("email")} placeholder="you@company.in" />
      <Field label="Password" type="password" value={f.password}
        onChange={set("password")} placeholder="At least 10 characters"
        hint="At least 10 characters. You'll be the finance owner of this organisation." />
      <Field label="Confirm password" type="password" value={f.confirm}
        onChange={set("confirm")} placeholder="Re-enter password" />
      {f.confirm.length > 0 && !matchOk && (
        <div className="tiny" style={{ color: "#c0392b", marginTop: 4 }}>Passwords don't match.</div>
      )}
      {err && <div className="hint" style={{ marginTop: 14 }}><Ic.x style={{ marginTop: 1, flex: "0 0 14px" }} /><div>{err}</div></div>}
      <button className="btn btn-primary btn-lg" type="submit" disabled={busy || !valid}
        style={{ width: "100%", justifyContent: "center", marginTop: 16, opacity: valid ? 1 : 0.55 }}>
        {busy ? "Creating your organisation…" : "Create account"}
      </button>
    </form>
  );
}

function LoginScreen({ onLogin, onGoogleLogin, onSignup }) {
  const [mode, setMode] = React.useState("login");   // 'login' | 'signup'
  const [err, setErr] = React.useState("");
  const [googleClientId, setGoogleClientId] = React.useState("");
  const [googleOn, setGoogleOn] = React.useState(false);   // show the Google button?
  // single-session: show why the previous device was signed out (set in api 401)
  const [superseded] = React.useState(() => {
    const v = sessionStorage.getItem("lekha_signout") === "superseded";
    sessionStorage.removeItem("lekha_signout");
    return v;
  });

  React.useEffect(() => {
    const desktop = !!(window.isDesktopApp && window.isDesktopApp());
    api.get("/api/auth/config")
      .then((c) => {
        setGoogleClientId(c.google_client_id || "");
        // desktop shows the button when the DESKTOP client is set; web when the web one is
        setGoogleOn(desktop ? !!c.google_desktop_client_id : !!c.google_client_id);
      })
      .catch(() => {});
  }, []);

  const onGoogleCredential = async (credential) => {
    setErr("");
    try {
      await onGoogleLogin(credential);
    } catch (_) {
      setErr("This Google account isn’t authorised for Lekha. Ask an admin to add it.");
    }
  };

  const switchMode = (m) => { setMode(m); setErr(""); };
  const signup = mode === "signup";

  return (
    <div style={{ minHeight: "100vh", background: "var(--bg)", display: "grid", placeItems: "center", padding: "32px 18px" }}>
      <div style={{ width: "min(440px, 100%)" }}>
        <div style={{ textAlign: "center", marginBottom: 18 }}>
          <div style={{ fontFamily: "var(--serif)", fontWeight: 800, fontSize: 34, color: "var(--lime-ink)" }}>Lekha AI</div>
          <div className="tiny" style={{ marginTop: 4 }}>Lekha AI books it.</div>
        </div>

        {superseded && (
          <div className="hint" style={{ marginBottom: 14 }}>
            <Ic.shield style={{ marginTop: 1, flex: "0 0 14px" }} />
            <div>You were signed out because your account was signed in on another device. Only one active session is allowed at a time.</div>
          </div>
        )}

        <div className="card card-pad">
          <div className="section-title" style={{ marginBottom: 2 }}>
            {signup ? "Create your organisation" : "Sign in"}
          </div>
          <div className="tiny" style={{ marginBottom: 6 }}>
            {signup
              ? "Register your company and become its finance owner."
              : "Welcome back — sign in to your account."}
          </div>

          {signup
            ? <SignUpForm onSignup={onSignup} err={err} setErr={setErr} />
            : <SignInForm onLogin={onLogin} err={err} setErr={setErr} />}

          {googleOn && !signup && (
            <div style={{ marginTop: 18 }}>
              <div className="row gap8" style={{ alignItems: "center", margin: "4px 0 14px" }}>
                <div style={{ flex: 1, height: 1, background: "var(--border)" }} />
                <span className="tiny">or</span>
                <div style={{ flex: 1, height: 1, background: "var(--border)" }} />
              </div>
              <GoogleButton clientId={googleClientId} onCredential={onGoogleCredential} />
            </div>
          )}

          <div className="tiny" style={{ marginTop: 18, textAlign: "center" }}>
            {signup ? (
              <span>Already have an account?{" "}
                <a href="#" onClick={(e) => { e.preventDefault(); switchMode("login"); }}
                  style={{ color: "var(--lime-ink)", fontWeight: 700 }}>Sign in</a>
              </span>
            ) : (
              <span>New to Lekha?{" "}
                <a href="#" onClick={(e) => { e.preventDefault(); switchMode("signup"); }}
                  style={{ color: "var(--lime-ink)", fontWeight: 700 }}>Create an account</a>
              </span>
            )}
          </div>
        </div>
      </div>
    </div>
  );
}

Object.assign(window, { LoginScreen });
