/* login.jsx — Last Rose gate. Native Cognito login (email + password + required
   TOTP), the ARES model. Premium; dark or light. Multi-step, driven by window.lrAuth:
     signin  ->  [new_password]  ->  [mfa_setup | mfa]  ->  onAuthed()
   The QR is drawn client-side from the otpauth URI (qrcode UMD lib from CDN); the
   secret is always shown too, so an authenticator app can be set up by manual entry. */

function QRImage({ text, size = 172 }) {
  const src = React.useMemo(() => {
    try {
      if (typeof window.qrcode !== "function" || !text) return "";
      const qr = window.qrcode(0, "M");
      qr.addData(text);
      qr.make();
      return qr.createDataURL(5, 4); // cellSize, margin -> data:image/gif
    } catch (e) { return ""; }
  }, [text]);
  if (!src) return null;
  return (
    <img src={src} width={size} height={size} alt="Authenticator QR code"
      style={{ borderRadius: 14, background: "#fff", padding: 10, boxShadow: "0 10px 30px -12px rgba(0,0,0,0.45)" }} />
  );
}

// Top-level (stable identity) so typing never remounts the input / drops focus.
function LoginField({ th, error, onClearError, inputRef, icon, type, value, onChange, placeholder, label, inputMode, maxLength, autoComplete }) {
  return (
    <div className="mb-3">
      <label className="mb-2 block text-[11px] font-semibold uppercase tracking-[0.22em]" style={{ color: th.sub }}>{label}</label>
      <div className="flex items-center gap-3 rounded-2xl border px-4 transition-[border-color,box-shadow]"
        style={{
          background: th.inputBg,
          borderColor: error ? "rgba(216,59,84,0.7)" : th.inputBorder,
          boxShadow: error ? "0 0 0 4px rgba(216,59,84,0.12)" : "none",
          height: 56,
        }}>
        <Icon name={icon} size={18} style={{ color: th.keyIcon }} />
        <input
          ref={inputRef} type={type} value={value}
          onChange={(e) => { onChange(e.target.value); if (error) onClearError(); }}
          placeholder={placeholder} autoComplete={autoComplete || "off"}
          inputMode={inputMode} maxLength={maxLength}
          className="h-full flex-1 bg-transparent text-[16px] tracking-wide outline-none"
          style={{ color: th.inputText }}
        />
      </div>
    </div>
  );
}

function LoginGate({ onAuthed, mode, onToggleTheme }) {
  const th = window.SHELL_THEMES[mode] || window.SHELL_THEMES.dark;

  const [step, setStep] = React.useState("signin"); // signin | new_password | mfa_setup | mfa
  const [email, setEmail] = React.useState("");
  const [password, setPassword] = React.useState("");
  const [newPw, setNewPw] = React.useState("");
  const [code, setCode] = React.useState("");
  const [session, setSession] = React.useState("");
  const [secret, setSecret] = React.useState("");
  const [otpauth, setOtpauth] = React.useState("");
  const [status, setStatus] = React.useState("idle"); // idle | loading | ok | error
  const [err, setErr] = React.useState("");
  const [shake, setShake] = React.useState(false);
  const firstRef = React.useRef(null);

  React.useEffect(() => {
    const t = setTimeout(() => firstRef.current && firstRef.current.focus(), 320);
    return () => clearTimeout(t);
  }, [step]);

  const isErr = status === "error";
  const clearErr = () => { setStatus("idle"); setErr(""); };

  function fail(msg) {
    setStatus("error"); setErr(msg || "Something went wrong. Please try again.");
    setShake(true); setTimeout(() => setShake(false), 460);
  }

  function advance(data) {
    if (!data || data.error) return fail(data && data.error);
    if (data.status === "ok") { setStatus("ok"); setTimeout(onAuthed, 520); return; }
    setStatus("idle"); setCode(""); setErr("");
    if (data.status === "new_password") { setSession(data.session || ""); setStep("new_password"); return; }
    if (data.status === "mfa_setup") {
      setSession(data.session || ""); setSecret(data.secret || ""); setOtpauth(data.otpauth || "");
      setStep("mfa_setup"); return;
    }
    if (data.status === "mfa") { setSession(data.session || ""); setStep("mfa"); return; }
    fail("Unexpected response. Please try again.");
  }

  async function submit(e) {
    e.preventDefault();
    if (status === "loading" || status === "ok") return;
    setStatus("loading"); setErr("");
    try {
      let data;
      if (step === "signin") data = await window.lrAuth.signin(email, password);
      else if (step === "new_password") data = await window.lrAuth.newPassword(email, session, newPw);
      else if (step === "mfa_setup") data = await window.lrAuth.mfaSetup(email, session, code);
      else data = await window.lrAuth.mfa(email, session, code);
      advance(data);
    } catch (e2) { fail("Network error. Please try again."); }
  }

  function startOver() {
    setStep("signin"); setPassword(""); setNewPw(""); setCode("");
    setSession(""); setSecret(""); setOtpauth(""); setStatus("idle"); setErr("");
  }

  const submitLabel = { signin: "Enter", new_password: "Set password", mfa_setup: "Verify & enter", mfa: "Verify" }[step];
  const heads = {
    signin: { h: <>A curated suite of<br />live product demos.</>, p: "Sign in with your email and password to step into the showroom." },
    new_password: { h: <>Set your password.</>, p: "Choose a new password of at least 12 characters, with an upper- and lower-case letter, a number and a symbol." },
    mfa_setup: { h: <>Set up your<br />authenticator.</>, p: "Scan the code with Google Authenticator, 1Password or Authy — or enter the key by hand — then type the current 6-digit code." },
    mfa: { h: <>Enter your<br />authenticator code.</>, p: "Open your authenticator app and enter the current 6-digit code for Last Rose." },
  }[step];

  const fp = { th, error: isErr, onClearError: clearErr }; // shared field props

  return (
    <div className="relative h-full w-full overflow-hidden a-fade" style={{ background: th.page, fontFamily: "'Manrope', sans-serif" }}>
      <div className="absolute right-5 top-5 z-20"><ThemeToggle mode={mode} onToggle={onToggleTheme} th={th} /></div>

      {/* ambient field */}
      <div className="pointer-events-none absolute inset-0">
        <div className="absolute -top-40 -right-32 h-[640px] w-[640px] rounded-full" style={{ background: `radial-gradient(circle, ${th.glow1}, transparent 62%)` }} />
        <div className="absolute -bottom-56 -left-40 h-[680px] w-[680px] rounded-full" style={{ background: `radial-gradient(circle, ${th.glow2}, transparent 60%)` }} />
      </div>

      {/* oversized botanical motif */}
      <div className="pointer-events-none absolute right-6 top-1/2 hidden -translate-y-1/2 md:block" style={{ opacity: th.motifOpacity }}>
        <RoseMark size={620} color={th.accent} petals={9} />
      </div>
      <div className="pointer-events-none absolute right-[34%] top-[18%] hidden lg:block" style={{ opacity: th.motifOpacity * 0.36 }}>
        <RoseMark size={180} color={th.accent} petals={7} />
      </div>

      {/* content */}
      <div className="relative z-10 flex h-full w-full items-center px-6 md:px-20">
        <div className="w-full max-w-md a-fade-up">
          {/* wordmark */}
          <div className="mb-10 flex items-center gap-4">
            <RoseMark size={62} color={th.accent} petals={6} />
            <div style={{ fontFamily: "'Pacifico', cursive", fontSize: 44, color: th.inkStrong, letterSpacing: "0.005em", lineHeight: 1.1, paddingBottom: 2 }}>Last Rose</div>
          </div>

          <h1 style={{ fontFamily: "'Spectral', serif", color: th.inkStrong }} className="text-[40px] font-medium leading-[1.06]">{heads.h}</h1>
          <p className="mt-4 max-w-sm text-[15px] leading-relaxed" style={{ color: th.ink }}>{heads.p}</p>

          <form onSubmit={submit} className="mt-8" style={shake ? { animation: "lr-shakekey .45s" } : undefined}>
            {step === "signin" && (
              <>
                <LoginField {...fp} inputRef={firstRef} icon="Mail" type="email" value={email} onChange={setEmail}
                  placeholder="you@company.com" label="Email" inputMode="email" autoComplete="username" />
                <LoginField {...fp} icon="KeyRound" type="password" value={password} onChange={setPassword}
                  placeholder="••••••••••" label="Password" autoComplete="current-password" />
              </>
            )}

            {step === "new_password" && (
              <LoginField {...fp} inputRef={firstRef} icon="KeyRound" type="password" value={newPw} onChange={setNewPw}
                placeholder="Your new password" label="New password" autoComplete="new-password" />
            )}

            {step === "mfa_setup" && (
              <div className="mb-3">
                {otpauth ? (
                  <div className="mb-4 flex items-center gap-4">
                    <QRImage text={otpauth} />
                    <div className="min-w-0">
                      <div className="text-[11px] font-semibold uppercase tracking-[0.18em]" style={{ color: th.sub }}>Setup key</div>
                      <div className="mt-1 select-all break-all font-mono text-[12.5px] leading-snug" style={{ color: th.ink }}>{secret}</div>
                      <div className="mt-2 text-[11px]" style={{ color: th.faint }}>Can't scan? Add the key manually in your app.</div>
                    </div>
                  </div>
                ) : null}
                <LoginField {...fp} inputRef={firstRef} icon="ShieldCheck" type="text" value={code} onChange={(v) => setCode(v.replace(/\D/g, ""))}
                  placeholder="123456" label="6-digit code" inputMode="numeric" maxLength={6} autoComplete="one-time-code" />
              </div>
            )}

            {step === "mfa" && (
              <LoginField {...fp} inputRef={firstRef} icon="ShieldCheck" type="text" value={code} onChange={(v) => setCode(v.replace(/\D/g, ""))}
                placeholder="123456" label="6-digit code" inputMode="numeric" maxLength={6} autoComplete="one-time-code" />
            )}

            <button type="submit" disabled={status === "loading" || status === "ok"}
              className="mt-2 flex h-[52px] w-full items-center justify-center gap-2 rounded-2xl text-[15px] font-semibold transition-transform active:scale-[0.985] disabled:opacity-90"
              style={{ background: status === "ok" ? "#3fae6a" : th.accent, color: "#fff", boxShadow: "0 12px 30px -12px rgba(216,59,84,0.75)" }}>
              {status === "loading" ? <Icon name="LoaderCircle" size={18} style={{ animation: "lr-spin 1s linear infinite" }} />
                : status === "ok" ? <><Icon name="Check" size={18} /> Welcome</>
                  : <>{submitLabel} <Icon name="ArrowRight" size={18} /></>}
            </button>

            <div className="mt-3 flex min-h-[20px] items-center justify-between text-[13px]">
              <span>
                {isErr && (
                  <span className="inline-flex items-center gap-1.5 a-fade" style={{ color: th.accentText }}>
                    <Icon name="CircleAlert" size={14} /> {err}
                  </span>
                )}
              </span>
              {step !== "signin" && status !== "ok" && (
                <button type="button" onClick={startOver} className="text-[12.5px] font-semibold underline-offset-2 hover:underline" style={{ color: th.sub }}>
                  Start over
                </button>
              )}
            </div>
          </form>
        </div>
      </div>

      <style>{`@keyframes lr-shakekey{10%,90%{transform:translateX(-1px)}20%,80%{transform:translateX(2px)}30%,50%,70%{transform:translateX(-5px)}40%,60%{transform:translateX(5px)}}`}</style>
    </div>
  );
}

window.LoginGate = LoginGate;
