// Vanday DAM — login screen
function LoginPage({ onLogin }) {
  const [email, setEmail] = React.useState("you@yourteam.com");
  const [password, setPassword] = React.useState("");
  const [error, setError] = React.useState(null);
  const [submitting, setSubmitting] = React.useState(false);

  // ---- Clerk integration --------------------------------------------------
  // Track whether the Clerk SDK has finished initialising. The HTML page
  // dispatches a `clerk-ready` event once Clerk.load() resolves.
  const [clerkReady, setClerkReady] = React.useState(window.__clerkReady === true);
  React.useEffect(() => {
    if (clerkReady) return;
    const onReady = () => setClerkReady(true);
    window.addEventListener("clerk-ready", onReady);
    return () => window.removeEventListener("clerk-ready", onReady);
  }, [clerkReady]);

  // Fetch the public deployment config to know whether to show Clerk
  // sign-up/sign-in (beta) or just the password form (dev).
  const [config, setConfig] = React.useState(null);
  React.useEffect(() => {
    let stop = false;
    fetch("/api/config").then((r) => r.ok ? r.json() : { mode: "beta", clerkSignupEnabled: true })
      .then((d) => { if (!stop) setConfig(d); })
      .catch(() => { if (!stop) setConfig({ mode: "beta", clerkSignupEnabled: true }); });
    return () => { stop = true; };
  }, []);
  const showClerk = config ? config.clerkSignupEnabled : true;

  // Helper: when a user signs in via Clerk, wipe any leftover legacy session
  // cookie from prior password logins. Otherwise the cookie can intercept
  // future requests on the server side, masking the Clerk identity entirely.
  // Then reload the page so all components remount with Clerk as the active
  // (and only) auth method.
  const completeClerkSignIn = React.useCallback(async () => {
    try { await fetch("/api/logout", { method: "POST" }); } catch {}
    // Hard reload: lets Clerk's session token attach to every request from
    // the very first fetch, including /api/me which is what creates the
    // user record and seeds demos.
    location.reload();
  }, []);

  // Once Clerk is ready, check if there's already a signed-in user — if so,
  // we just advance into the app instead of asking them to sign in again.
  // Also listen for sign-in events so Google/email/password flows in the
  // Clerk modal automatically log the user into Vanday.
  React.useEffect(() => {
    if (!clerkReady || !window.Clerk) return;
    if (window.Clerk.user) { onLogin(); return; }
    const unsub = window.Clerk.addListener(({ user }) => {
      // Run the full sign-in completion on FIRST observation of a user.
      if (user) completeClerkSignIn();
    });
    return () => { try { unsub && unsub(); } catch {} };
  }, [clerkReady, onLogin, completeClerkSignIn]);

  const openClerkSignIn = () => {
    if (!window.Clerk) return;
    // If they're already signed in (e.g. just came back from a Google flow),
    // skip the modal and let them straight into the app.
    if (window.Clerk.user) { onLogin(); return; }
    window.Clerk.openSignIn({});
  };
  const openClerkSignUp = () => {
    if (!window.Clerk) return;
    if (window.Clerk.user) { onLogin(); return; }
    window.Clerk.openSignUp({});
  };

  // Invitees arrive via the email link (…/?join=invite). They don't have a
  // password — they need to CREATE an account with the invited email, after
  // which the server auto-joins them to the workspace. So when we see that
  // flag we lead with sign-up and open the Clerk sign-up form automatically.
  const invited = React.useMemo(() => {
    try { return new URLSearchParams(window.location.search).get("join") === "invite"; }
    catch { return false; }
  }, []);
  // Workspace the invitee is joining, passed as ?w= on the invite link. Used to
  // personalize the sign-up copy ("…for the Acme workspace").
  const inviteWorkspace = React.useMemo(() => {
    try {
      const w = new URLSearchParams(window.location.search).get("w");
      return w ? w.slice(0, 80) : null;
    } catch { return null; }
  }, []);
  // Stash the invite id (?i=) so it survives the Clerk sign-up popup AND the
  // page reload in completeClerkSignIn(). jfetch reads this and sends it as the
  // X-Vanday-Invite header so the server can validate the invitee's email
  // matches the invite (and auto-join them to the right workspace).
  React.useEffect(() => {
    try {
      const params = new URLSearchParams(window.location.search);
      if (params.get("join") === "invite") {
        const i = params.get("i");
        if (i) window.sessionStorage.setItem("vanday_invite_id", i);
      }
    } catch {}
  }, []);
  const autoOpenedSignUp = React.useRef(false);
  React.useEffect(() => {
    if (!invited || !showClerk) return;
    if (!clerkReady || !window.Clerk || autoOpenedSignUp.current) return;
    if (window.Clerk.user) return; // already signed in — the other effect advances them
    autoOpenedSignUp.current = true;
    window.Clerk.openSignUp({});
  }, [invited, showClerk, clerkReady]);

  // 8-tile asymmetric mosaic (Option C design refresh): five landscape
  // scenes interleaved with three team portraits. Each tile is placed via
  // its m-1..m-8 class in styles.css — order matters because the grid is
  // designed around portrait vs. landscape orientations per cell.
  const MOSAIC_TILES = [
    { cls: "m-1", src: "https://images.unsplash.com/photo-1464822759023-fed622ff2c3b?w=900&q=70&auto=format&fit=crop" },        // Alps, landscape
    { cls: "m-2", src: "https://images.unsplash.com/photo-1438761681033-6461ffad8d80?w=600&q=70&auto=format&fit=crop" },        // portrait
    { cls: "m-3", src: "https://images.unsplash.com/photo-1521540216272-a50305cd4421?w=600&q=70&auto=format&fit=crop" },        // blossom
    { cls: "m-4", src: "https://images.unsplash.com/photo-1500648767791-00dcc994a43e?w=600&q=70&auto=format&fit=crop" },        // portrait
    { cls: "m-5", src: "https://images.unsplash.com/photo-1517022812141-23620dba5c23?w=900&q=70&auto=format&fit=crop" },        // horses
    { cls: "m-6", src: "https://images.unsplash.com/photo-1531123897727-8f129e1688ce?w=600&q=70&auto=format&fit=crop" },        // portrait
    { cls: "m-7", src: "https://images.unsplash.com/photo-1518709268805-4e9042af2176?w=600&q=70&auto=format&fit=crop" },        // arches
    { cls: "m-8", src: "https://images.unsplash.com/photo-1501594907352-04cda38ebc29?w=900&q=70&auto=format&fit=crop" },        // city/Lombard
  ];

  const submit = async (e) => {
    e.preventDefault();
    setError(null);
    setSubmitting(true);
    try {
      const r = await fetch("/api/login", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ password }),
      });
      if (r.status === 401) {
        setError("Wrong password.");
      } else if (!r.ok) {
        setError(`Couldn't reach the server (${r.status}). Is it running?`);
      } else {
        onLogin();
      }
    } catch (err) {
      setError("Couldn't reach the server. Is it running?");
    } finally {
      setSubmitting(false);
    }
  };

  return (
    <div className="login">
      <div className="login-form-side">
        <div className="login-brand">
          <div className="login-brand-mark">v.</div>
          <span>Vanday</span>
        </div>

        <div className="login-form-wrap">
          <h1 className="login-h">
            {invited ? "You're invited." : (showClerk ? "Try the Vanday beta." : "Welcome back.")}
          </h1>
          <p className="login-sub">
            {invited
              ? (inviteWorkspace
                  ? `Create your account to join the ${inviteWorkspace} workspace.`
                  : "Create your account to join your team library.")
              : (showClerk
                  ? "Sign up free and put your whole photo library to work — auto-tagged, cropped, and instantly searchable."
                  : "Sign in to your team library.")}
          </p>

          {invited && showClerk && (
            <div
              style={{
                background: "var(--surface-2, #f5f3ff)",
                border: "1px solid var(--border)",
                borderRadius: 10,
                padding: "14px 16px",
                marginBottom: 18,
                fontSize: 13.5,
              }}
            >
              <div style={{ fontWeight: 600, marginBottom: 4 }}>
                {inviteWorkspace ? `You've been invited to ${inviteWorkspace} 🎉` : "You've been invited to a workspace 🎉"}
              </div>
              <div style={{ color: "var(--text-muted)", marginBottom: 12 }}>
                Sign up with the email address your invite was sent to and you'll join your team automatically. You don't need a password yet — you'll create one now.
              </div>
              <button
                type="button"
                className="btn primary btn-block"
                onClick={openClerkSignUp}
                disabled={!clerkReady}
                title={clerkReady ? "Create your Vanday account" : "Loading…"}
              >
                {clerkReady ? "Create your account" : "Loading…"}
              </button>
              <div style={{ marginTop: 10, textAlign: "center", fontSize: 12.5, color: "var(--text-faint)" }}>
                Already have an account?{" "}
                <a
                  href="#"
                  onClick={(e) => { e.preventDefault(); openClerkSignIn(); }}
                  style={{ color: "var(--brand)", fontWeight: 500 }}
                >
                  Sign in
                </a>
              </div>
            </div>
          )}

          {!invited && showClerk && (
            <div
              style={{
                background: "var(--surface-2, #f5f3ff)",
                border: "1px solid var(--border)",
                borderRadius: 10,
                padding: "14px 16px",
                marginBottom: 18,
                fontSize: 13.5,
              }}
            >
              <div style={{ fontWeight: 600, marginBottom: 4 }}>
                Vanday is in free beta 🎉
              </div>
              <div style={{ color: "var(--text-muted)", marginBottom: 12 }}>
                Create your account to start uploading — no credit card, no setup. Your team library is ready in minutes.
              </div>
              <button
                type="button"
                className="btn primary btn-block"
                onClick={openClerkSignUp}
                disabled={!clerkReady}
                title={clerkReady ? "Create your Vanday account" : "Loading…"}
              >
                {clerkReady ? "Try the beta now" : "Loading…"}
              </button>
              <div style={{ marginTop: 10, textAlign: "center", fontSize: 12.5, color: "var(--text-faint)" }}>
                Already have an account?{" "}
                <a
                  href="#"
                  onClick={(e) => { e.preventDefault(); openClerkSignIn(); }}
                  style={{ color: "var(--brand)", fontWeight: 500 }}
                >
                  Sign in
                </a>
              </div>
            </div>
          )}

          <form onSubmit={submit}>
            <div className="field">
              <label htmlFor="email">Work email</label>
              <input
                id="email"
                type="email"
                value={email}
                onChange={(e) => setEmail(e.target.value)}
                autoComplete="email"
              />
            </div>
            <div className="field">
              <label htmlFor="password">Password</label>
              <input
                id="password"
                type="password"
                value={password}
                onChange={(e) => setPassword(e.target.value)}
                autoComplete="current-password"
                autoFocus
                placeholder="Enter your password"
              />
            </div>

            {error && (
              <div style={{ color: "oklch(0.65 0.2 24)", fontSize: 12.5, marginBottom: 12 }}>
                {error}
              </div>
            )}

            <button
              type="submit"
              className="btn primary btn-block"
              disabled={submitting || !password}
            >
              {submitting ? "Signing in…" : "Sign in"}
            </button>

            {showClerk && (
              <>
                <div className="divider">or continue with</div>

                <button
                  type="button"
                  className="btn btn-block"
                  onClick={openClerkSignIn}
                  disabled={!clerkReady}
                  title={clerkReady ? "Sign in with Google via Clerk" : "Loading…"}
                >
                  <IcGoogle size={15} /> Continue with Google
                </button>

                <div style={{ marginTop: 18, textAlign: "center", fontSize: 13 }}>
                  New to Vanday?{" "}
                  <a
                    href="#"
                    onClick={(e) => { e.preventDefault(); openClerkSignUp(); }}
                    style={{ color: "var(--brand)", fontWeight: 500 }}
                  >
                    Create an account
                  </a>
                </div>
              </>
            )}
            {config && config.mode === "dev" && (
              <div style={{ marginTop: 18, textAlign: "center", fontSize: 12, color: "var(--text-faint)" }}>
                Dev build · password-only
              </div>
            )}
          </form>
        </div>

        <div className="login-foot">
          <span>© 2026 Vanday, Inc.</span>
          <span>
            <a href="#">Privacy</a> &nbsp;·&nbsp; <a href="#">Terms</a> &nbsp;·&nbsp;{" "}
            <a href="#">Help</a>
          </span>
        </div>
      </div>

      <div className="login-art-side">
        <div className="login-mosaic">
          {MOSAIC_TILES.map((t) => (
            <div
              key={t.cls}
              className={`login-m-tile ${t.cls}`}
              style={{ backgroundImage: `url('${t.src}')` }}
            />
          ))}
        </div>
        <div className="login-art-overlay" />
        <div className="login-art-content">
          <h2 className="login-art-h">
            Found <em>in a glance</em> — every shot from Tuscany to the Tidal Basin.
          </h2>
          <p className="login-art-p">
            Vanday auto-tags, crops and serves your team's images. Spend more time shooting, less time hunting.
          </p>
        </div>
      </div>
    </div>
  );
}

window.LoginPage = LoginPage;
