// Auth UI — top-bar pill + magic-link modal.
// useForgeAuth(): live subscription to the auth state.
// AuthPill: renders email + sign out, or "Sign in" to open the modal.

const { useState: useAuthState, useEffect: useAuthEffect, useCallback: useAuthCb } = React;

function useForgeAuth() {
  const enabled = window.ForgeAuth && window.ForgeAuth.isEnabled();
  const [user, setUser] = useAuthState(() =>
    enabled ? window.ForgeAuth.getUser() : null,
  );
  useAuthEffect(() => {
    if (!enabled) return;
    return window.ForgeAuth.subscribe(setUser);
  }, [enabled]);
  return { enabled, user };
}

function AuthPill() {
  const { enabled, user } = useForgeAuth();
  const [open, setOpen] = useAuthState(false);

  if (!enabled) {
    return (
      <span
        title="Set FORGE_CONFIG.supabaseUrl + supabaseAnonKey to enable accounts."
        style={{
          fontFamily: "JetBrains Mono, monospace",
          fontSize: 10,
          letterSpacing: "0.14em",
          textTransform: "uppercase",
          color: "var(--muted)",
        }}
      >
        Local · no account
      </span>
    );
  }

  if (user) {
    return (
      <div style={{ display: "flex", alignItems: "center", gap: 10 }}>
        <span
          style={{
            display: "inline-flex",
            alignItems: "center",
            gap: 6,
            padding: "5px 10px",
            borderRadius: 999,
            border: "1px solid var(--border)",
            fontSize: 12,
            color: "var(--ink)",
          }}
        >
          <span style={{ width: 6, height: 6, borderRadius: 999, background: "var(--accent)" }} />
          {user.email}
        </span>
        <button
          onClick={() => window.ForgeAuth.signOut()}
          style={{
            background: "transparent",
            border: "1px solid var(--border)",
            color: "var(--muted)",
            padding: "5px 12px",
            borderRadius: 999,
            fontSize: 12,
            cursor: "pointer",
          }}
        >
          Sign out
        </button>
      </div>
    );
  }

  return (
    <>
      <button
        onClick={() => setOpen(true)}
        style={{
          background: "var(--accent)",
          color: "#14180A",
          border: "none",
          padding: "7px 14px",
          borderRadius: 999,
          fontSize: 13,
          fontWeight: 500,
          cursor: "pointer",
        }}
      >
        Sign in
      </button>
      {open && <SignInModal onClose={() => setOpen(false)} />}
    </>
  );
}

function SignInModal({ onClose }) {
  const [email, setEmail] = useAuthState("");
  const [sending, setSending] = useAuthState(false);
  const [sent, setSent] = useAuthState(false);
  const [err, setErr] = useAuthState(null);

  const submit = useAuthCb(async (e) => {
    e.preventDefault();
    if (!email) return;
    setSending(true);
    setErr(null);
    const { error } = await window.ForgeAuth.signInWithMagicLink(email);
    setSending(false);
    if (error) setErr(error.message);
    else setSent(true);
  }, [email]);

  return (
    <div
      onClick={onClose}
      style={{
        position: "fixed", inset: 0, background: "rgba(0,0,0,0.6)",
        display: "flex", alignItems: "center", justifyContent: "center",
        zIndex: 200, padding: 20,
      }}
    >
      <div
        onClick={(e) => e.stopPropagation()}
        style={{
          background: "var(--paper)",
          border: "1px solid var(--border)",
          borderRadius: 14,
          padding: 32,
          width: "100%",
          maxWidth: 420,
          color: "var(--ink)",
        }}
      >
        <div style={{ fontFamily: "JetBrains Mono, monospace", fontSize: 10, letterSpacing: "0.18em", textTransform: "uppercase", color: "var(--accent)" }}>
          — Sign in
        </div>
        <h2 style={{ fontFamily: "Newsreader, serif", fontWeight: 400, fontSize: 28, margin: "10px 0 6px", letterSpacing: "-0.01em" }}>
          {sent ? "Check your inbox." : "Email a sign-in link."}
        </h2>
        <p style={{ color: "var(--muted)", fontSize: 14, lineHeight: 1.5, margin: "0 0 20px" }}>
          {sent
            ? `Sent a link to ${email}. Open it on this device to finish.`
            : "We'll send a magic link. No password required."}
        </p>
        {!sent && (
          <form onSubmit={submit}>
            <input
              type="email"
              autoFocus
              required
              value={email}
              onChange={(e) => setEmail(e.target.value)}
              placeholder="you@work.com"
              style={{
                width: "100%",
                padding: "12px 14px",
                background: "var(--paper-2)",
                border: "1px solid var(--border)",
                borderRadius: 8,
                color: "var(--ink)",
                fontSize: 14,
                marginBottom: 12,
              }}
            />
            <button
              type="submit"
              disabled={sending}
              style={{
                width: "100%",
                background: "var(--accent)",
                color: "#14180A",
                border: "none",
                padding: "11px 16px",
                borderRadius: 999,
                fontSize: 14,
                fontWeight: 500,
                cursor: sending ? "default" : "pointer",
                opacity: sending ? 0.6 : 1,
              }}
            >
              {sending ? "Sending…" : "Send link"}
            </button>
            {err && (
              <div style={{ marginTop: 10, color: "#E08A6B", fontSize: 13 }}>
                {err}
              </div>
            )}
          </form>
        )}
        <button
          onClick={onClose}
          style={{
            marginTop: 18,
            background: "transparent",
            border: "none",
            color: "var(--muted)",
            fontSize: 13,
            cursor: "pointer",
          }}
        >
          Close
        </button>
      </div>
    </div>
  );
}

window.AuthPill = AuthPill;
window.useForgeAuth = useForgeAuth;
