// MostlyQR — sign-in (passwordless magic link). Talks to @mostly-tiny/auth's
// sendMagicLink callable via window.MQRApi. Real auth only — no demo/mock-dashboard
// bypass: the server-side allow-list (auth.config: only hi@maxcelar.com) gates every
// sign-in, and access is CLOSED to the public (PUBLIC_APP_OPEN=false hides this page in nav).
const I18N = (typeof window !== 'undefined' && window.ForgeI18n) || { t: (k) => k, has: () => false, locale: 'en', dir: 'ltr', fmt: { number: (n)=>String(n??''), currency:(n)=>String(n??''), percent:(n)=>String(n??''), date:(d)=>String(d??''), time:(d)=>String(d??''), relative:(d)=>String(d??'') } };
const tr = I18N.t, fmt = I18N.fmt;
const LOCALE = I18N.locale;
const { Icon, MQMark, Wordmark } = window.MQR;
const F = window.ForgeDesignSystem_e40d74;
const { Button, Field, Input } = F;
const Api = window.MQRApi;
// Legal policy links (privacy/terms), rendered on the active locale — see shared.jsx.
const L = (typeof window !== 'undefined' && window.MQRLegal) || { url: () => "https://mostlyprivacy.com" };

// Google "G" mark — shown on the "Continue with Google" button (only rendered
// when Api.google is enabled). Copied from the shared Auth component.
const Google = () => <svg width="16" height="16" viewBox="0 0 24 24"><path fill="#4285F4" d="M22.5 12.2c0-.7-.1-1.4-.2-2H12v3.9h5.9a5 5 0 0 1-2.2 3.3v2.7h3.6c2.1-2 3.2-4.8 3.2-7.9z"/><path fill="#34A853" d="M12 23c2.9 0 5.4-1 7.2-2.6l-3.6-2.7c-1 .7-2.3 1.1-3.6 1.1-2.8 0-5.1-1.9-6-4.4H2.3v2.8A11 11 0 0 0 12 23z"/><path fill="#FBBC05" d="M6 14.4a6.6 6.6 0 0 1 0-4.2V7.4H2.3a11 11 0 0 0 0 9.8z"/><path fill="#EA4335" d="M12 5.6c1.6 0 3 .5 4.1 1.6l3.1-3.1A11 11 0 0 0 2.3 7.4L6 10.2C6.9 7.6 9.2 5.6 12 5.6z"/></svg>;

function SignIn() {
  const [email, setEmail] = React.useState("");
  const [phase, setPhase] = React.useState("idle"); // idle | sending | sent | completing | error
  const [err, setErr] = React.useState(null);

  // Auth return: complete sign-in (magic-link OR "Sign in with Mostly Tiny"), then go on.
  // The IdP SSO redirect lands back on /signin with a #token fragment.
  // A refusal because the product is still in private beta (team allow-list) gets a calm
  // "not open yet" panel, not a raw error.
  const failTo = (e) => {
    if (window.MostlyAuth && MostlyAuth.isClosedBetaError && MostlyAuth.isClosedBetaError(e)) { setPhase("closed"); return; }
    setErr(String((e && e.message) || e)); setPhase("error");
  };

  React.useEffect(() => {
    const onDone = () => window.location.assign("/dashboard");
    const onFail = failTo;
    if (Api.isMagicLinkLanding()) {
      setPhase("completing");
      Api.completeMagicLink().then(onDone).catch(onFail);
    } else if (Api.isIdentityLanding && Api.isIdentityLanding()) {
      setPhase("completing");
      Api.completeIdentitySignIn().then(onDone).catch(onFail);
    }
  }, []);

  // "Continue with Mostly Tiny" → redirect to the IdP (navigates away; never resolves).
  const ssoAuth = () => {
    setErr(null);
    try { Api.startIdentitySignIn(); } catch (e2) { failTo(e2); }
  };

  const submit = async (e) => {
    e.preventDefault();
    if (!email.trim()) return;
    setPhase("sending"); setErr(null);
    try {
      await Api.requestMagicLink(email.trim());
      setPhase("sent");
    } catch (e2) { failTo(e2); }
  };

  // Google sign-in via the shared auth kit (window.MostlyAuth → Api.signInWithGoogle).
  // The team allow-list is enforced server-side by the auth blocking functions, so a
  // non-allowed Google account is rejected during the popup. Closing the popup is a
  // no-op (not an error).
  const googleAuth = async () => {
    setErr(null);
    try {
      await Api.signInWithGoogle();
      window.location.assign("/dashboard");
    } catch (e2) {
      const code = e2 && e2.code;
      if (code === "auth/popup-closed-by-user" || code === "auth/cancelled-popup-request") return;
      failTo(e2);
    }
  };

  return (
    <div className="ap-auth">
      <div className="ap-authcard">
        <div className="ap-authcard__brand"><a className="forge-appheader__brand" href="index.html"><MQMark s={34} animate /><Wordmark size={20} /></a></div>

        {phase === "completing" ? (
          <div className="ap-sent">
            <div className="ap-sent__ic"><Icon name="refresh" size={22} sw={2.2} /></div>
            <h1>{tr('mqr.signin.completing.title')}</h1>
            <p className="sub">{tr('mqr.signin.completing.sub')}</p>
          </div>
        ) : phase === "closed" ? (
          <div className="ap-sent">
            <div className="ap-sent__ic"><Icon name="lock" size={22} sw={2.2} /></div>
            <h1>Not open just yet</h1>
            <p className="sub">MostlyQR is in private beta — public sign-ups aren’t open yet. We’ll let you in soon.</p>
          </div>
        ) : phase === "sent" ? (
          <div className="ap-sent">
            <div className="ap-sent__ic"><Icon name="check" size={24} sw={2.4} /></div>
            <h1>{tr('mqr.signin.sent.title')}</h1>
            <p className="sub">
              {tr('mqr.signin.sent.body.1')} <strong style={{ color: "var(--fg)" }}>{email}</strong>{tr('mqr.signin.sent.body.2')}
            </p>
            <div style={{ marginTop: 12 }}>
              <button className="ap-link" style={{ border: "none", background: "none", cursor: "pointer" }}
                onClick={() => setPhase("idle")}>{tr('mqr.signin.sent.different')}</button>
            </div>
          </div>
        ) : (
          <>
            <h1>{tr('mqr.signin.title')}</h1>
            {Api.identitySSO ? (
              <>
                <p className="sub">One Mostly&nbsp;Tiny ID signs you in across every product — no password.</p>
                {phase === "error" && <div style={{ marginBottom: 12, color: "var(--danger, #b3261e)", fontSize: 13 }}>{err || tr('mqr.signin.error')}</div>}
                <Button variant="primary" size="lg" block onClick={ssoAuth}
                  iconRight={<Icon name="arrow" size={16} />}>
                  Continue with Mostly Tiny
                </Button>
              </>
            ) : (
              <>
                <p className="sub">{tr('mqr.signin.sub')}</p>
                {Api.google && (
                  <Button variant="secondary" size="lg" block iconLeft={<Google />} onClick={googleAuth}
                    disabled={phase === "sending" || phase === "completing"}>
                    {tr('auth.signin.google')}
                  </Button>
                )}
                <form className="ap-form" onSubmit={submit}>
                  <Field label={tr('mqr.signin.email')} error={phase === "error" ? (err || tr('mqr.signin.error')) : undefined}>
                    <Input type="email" placeholder="you@studio.com" value={email}
                      onChange={(e) => setEmail(e.target.value)} autoFocus />
                  </Field>
                  <Button variant="primary" size="lg" block type="submit"
                    disabled={phase === "sending"}
                    iconRight={phase === "sending" ? undefined : <Icon name="arrow" size={16} />}>
                    {phase === "sending" ? tr('mqr.signin.sending') : tr('mqr.signin.send')}
                  </Button>
                </form>
              </>
            )}
            <div className="ap-auth__promise">
              <Icon name="infinity" size={15} sw={2.2} /> {tr('mqr.signin.promise')}
            </div>
            <p className="ap-auth__legal" style={{ marginTop: 14, fontSize: 12, lineHeight: 1.5, color: "var(--fg-muted, #6b7280)", textAlign: "center" }}>
              {tr('mqr.signin.legal.pre')}{" "}
              <a className="ap-link" href={L.url('terms', LOCALE)} target="_blank" rel="noopener">{tr('mqr.landing.footer.link.terms')}</a>
              {" "}{tr('mqr.signin.legal.and')}{" "}
              <a className="ap-link" href={L.url('privacy', LOCALE)} target="_blank" rel="noopener">{tr('mqr.landing.footer.link.privacy')}</a>.
            </p>
          </>
        )}

        <div className="ap-auth__foot">
          <span style={{ display: "inline-flex", alignItems: "center", gap: 6 }}>
            {tr('mqr.signin.foot.1')} <a className="ap-link" href="/builder">{tr('mqr.signin.foot.link')}</a>
          </span>
        </div>
      </div>
    </div>
  );
}

ReactDOM.createRoot(document.getElementById("mqr-app")).render(<SignIn />);
