// AuthFlow.jsx — interactive email-code sign-in flow.
// Email screen → code screen → success screen. Test code: 7K3PQ9.

const { useState, useEffect, useRef } = React;

/* ====================================================================== */
/* Shared state hook                                                      */
/* ====================================================================== */
const COUNTDOWN_SECONDS = 180;

// useAuthState drives the email → code → success state machine. When `api` is
// provided (api.requestCode, api.verifyCode), submitEmail/submitCode/resend
// hit the live backend instead of the demo no-op. When `api` is omitted, the
// hook stays in demo mode so the design canvas keeps working unchanged.
const useAuthState = ({ api } = {}) => {
  const [step, setStep] = useState("email");
  const [email, setEmail] = useState("");
  const [code, setCode] = useState(["", "", "", "", "", ""]);
  const [error, setError] = useState("");
  const [secondsLeft, setSecondsLeft] = useState(COUNTDOWN_SECONDS);
  const [resendFlash, setResendFlash] = useState(false);
  const [busy, setBusy] = useState(false);

  useEffect(() => {
    if (step !== "code" || secondsLeft <= 0) return;
    const t = setInterval(() => setSecondsLeft((s) => Math.max(0, s - 1)), 1000);
    return () => clearInterval(t);
  }, [step, secondsLeft]);

  const submitEmail = async (e) => {
    e?.preventDefault?.();
    if (!/^\S+@\S+\.\S+$/.test(email)) {
      setError("Please enter a valid email address.");
      return;
    }
    setError("");
    if (api?.requestCode) {
      setBusy(true);
      try {
        await api.requestCode(email);
      } catch (err) {
        setBusy(false);
        setError(err?.message || "Could not send code. Please try again.");
        return;
      }
      setBusy(false);
    }
    setCode(["", "", "", "", "", ""]);
    setSecondsLeft(COUNTDOWN_SECONDS);
    setStep("code");
  };

  const submitCode = async (eOrValue) => {
    let v;
    if (eOrValue && typeof eOrValue.preventDefault === "function") {
      eOrValue.preventDefault();
      v = code.join("").toUpperCase();
    } else if (typeof eOrValue === "string") {
      v = eOrValue.toUpperCase();
    } else {
      v = code.join("").toUpperCase();
    }
    if (v.length < 6) {
      setError("Enter all six characters.");
      return;
    }
    setError("");
    if (api?.verifyCode) {
      setBusy(true);
      try {
        await api.verifyCode(email, v);
      } catch (err) {
        setBusy(false);
        setError(err?.message || "Invalid or expired code.");
        return;
      }
      setBusy(false);
    }
    setStep("success");
  };

  const resend = async () => {
    setError("");
    if (api?.requestCode) {
      try {
        await api.requestCode(email);
      } catch (err) {
        setError(err?.message || "Could not resend code. Please try again.");
        return;
      }
    }
    setSecondsLeft(COUNTDOWN_SECONDS);
    setResendFlash(true);
    setTimeout(() => setResendFlash(false), 1400);
  };

  const changeEmail = () => {
    setStep("email");
    setError("");
    setCode(["", "", "", "", "", ""]);
  };

  const reset = () => {
    setStep("email");
    setEmail("");
    setCode(["", "", "", "", "", ""]);
    setError("");
    setSecondsLeft(COUNTDOWN_SECONDS);
  };

  return {
    step, setStep,
    email, setEmail,
    code, setCode,
    error, setError,
    secondsLeft, resendFlash, busy,
    submitEmail, submitCode, resend, changeEmail, reset,
  };
};

const fmtTime = (s) => {
  const m = Math.floor(s / 60);
  const sec = s % 60;
  return m + ":" + String(sec).padStart(2, "0");
};

/* ====================================================================== */
/* CodeBoxes — six independent inputs, paste-aware                        */
/* ====================================================================== */
const CodeBoxes = ({ value, onChange, error, autoFocus, big, onComplete }) => {
  const refs = useRef([]);

  const setIdx = (i, ch) => {
    const next = [...value];
    next[i] = ch;
    onChange(next);
  };

  const onInput = (i) => (e) => {
    const ch = e.target.value.toUpperCase().replace(/[^A-Z0-9]/g, "").slice(-1);
    setIdx(i, ch);
    if (ch && i < 5) refs.current[i + 1]?.focus();
  };

  const onKey = (i) => (e) => {
    if (e.key === "Backspace" && !value[i] && i > 0) {
      e.preventDefault();
      const next = [...value];
      next[i - 1] = "";
      onChange(next);
      refs.current[i - 1]?.focus();
    } else if (e.key === "ArrowLeft" && i > 0) {
      e.preventDefault();
      refs.current[i - 1]?.focus();
    } else if (e.key === "ArrowRight" && i < 5) {
      e.preventDefault();
      refs.current[i + 1]?.focus();
    }
  };

  const onPaste = (e) => {
    const txt = (e.clipboardData?.getData("text") || "")
      .toUpperCase()
      .replace(/[^A-Z0-9]/g, "")
      .slice(0, 6);
    if (!txt) return;
    e.preventDefault();
    const arr = ["", "", "", "", "", ""];
    for (let i = 0; i < txt.length; i++) arr[i] = txt[i];
    onChange(arr);
    const last = Math.min(txt.length, 5);
    refs.current[last]?.focus();
    if (txt.length === 6) setTimeout(() => onComplete?.(txt), 750);
  };

  const cls = [
    "auth-code-row",
    big ? "auth-code-row--big" : "",
    error ? "auth-code-row--error" : "",
  ].join(" ");

  return (
    <div className={cls}>
      {Array.from({ length: 6 }).map((_, i) => (
        <input
          key={i}
          ref={(r) => (refs.current[i] = r)}
          type="text"
          inputMode="text"
          autoCapitalize="characters"
          autoComplete={i === 0 ? "one-time-code" : "off"}
          maxLength={1}
          value={value[i]}
          onChange={onInput(i)}
          onKeyDown={onKey(i)}
          onPaste={onPaste}
          autoFocus={autoFocus && i === 0}
          placeholder=" "
          aria-label={"Character " + (i + 1)}
        />
      ))}
    </div>
  );
};

/* ====================================================================== */
/* Inline logos                                                            */
/* ====================================================================== */
const Wordmark = ({ color }) => (
  <img src="assets/logos/redbit-logo-red-dark.svg" alt="RedBit"
       style={{ height: 22, display: "block" }} />
);

const CheckIcon = () => (
  <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.6"
       strokeLinecap="round" strokeLinejoin="round">
    <path d="M5 12.5l4.5 4.5L19 7.5"></path>
  </svg>
);

/* ====================================================================== */
/* AuthFlow — email → code → success                                       */
/* ====================================================================== */
const AuthFlow = ({ initialStep, api }) => {
  const s = useAuthState({ api });
  useEffect(() => { if (initialStep) s.setStep(initialStep); /* eslint-disable-next-line */ }, []);

  return (
    <div className="auth-frame">
      <div className="auth-stage">
        {s.step === "email" && (
          <form className="auth-card" onSubmit={s.submitEmail}>
            <div className="auth-lockup">
              <Wordmark />
              <span style={{ marginLeft: "auto", fontSize: 11, color: "var(--fg-3)", letterSpacing: "0.16em", textTransform: "uppercase", fontWeight: 700 }}>Sign in</span>
            </div>
            <div className="auth-heading">
              <h1 className="auth-title">Sign in to continue</h1>
              <p className="auth-sub">Enter your email and we'll send a 6-character code.</p>
            </div>
            <div className="auth-field">
              <label className="auth-field__label" htmlFor="emailB">Email address</label>
              <input id="emailB" type="email" className="auth-input"
                     placeholder="you@company.com"
                     value={s.email} onChange={(e) => s.setEmail(e.target.value)} autoFocus />
              {s.error && <div className="auth-error">{s.error}</div>}
            </div>
            <button type="submit" className="auth-btn auth-btn--primary" disabled={s.busy}>
              {s.busy ? "Sending…" : "Send sign-in code"}
            </button>
          </form>
        )}

        {s.step === "code" && (
          <form className="auth-card" onSubmit={s.submitCode}>
            <div className="auth-lockup">
              <Wordmark />
              <span style={{ marginLeft: "auto", fontSize: 11, color: "var(--fg-3)", letterSpacing: "0.16em", textTransform: "uppercase", fontWeight: 700 }}>Verify · 2/2</span>
            </div>
            <div className="auth-heading">
              <h1 className="auth-title">Enter your code.</h1>
              <p className="auth-sub">
                Sent to <span className="auth-email-pill">{s.email || "you@company.com"}</span>
              </p>
            </div>
            <div className="auth-field">
              <div className="auth-codetop">
                <span className="auth-field__label">6-character code</span>
                <span className={"auth-countdown " + (s.secondsLeft <= 0 ? "auth-countdown--expired" : "")}>
                  <span className="auth-countdown__dot"></span>
                  {s.secondsLeft > 0 ? fmtTime(s.secondsLeft) + " left" : "Expired"}
                </span>
              </div>
              <CodeBoxes value={s.code} onChange={s.setCode} error={!!s.error} autoFocus onComplete={s.submitCode} />
              <div className="auth-paste">
                <kbd>⌘V</kbd>
                <span>auto-fills if you paste the whole code</span>
              </div>
              {s.error && <div className="auth-error">{s.error}</div>}
            </div>
            <button type="submit" className="auth-btn auth-btn--primary"
                    disabled={s.busy || s.code.join("").length < 6}>
              {s.busy ? "Verifying…" : "Verify code"}
            </button>
            <div style={{ display: "flex", justifyContent: "space-between", gap: 8, marginTop: -2 }}>
              <button type="button" className="auth-link auth-link--muted" onClick={s.changeEmail}>
                ← Change email
              </button>
              <button type="button" className="auth-link" onClick={s.resend} disabled={s.busy}>
                {s.resendFlash ? "Sent ✓" : "Resend code"}
              </button>
            </div>
          </form>
        )}

        {s.step === "success" && (
          <div className="auth-card" style={{ alignItems: "center", textAlign: "center", padding: "44px 32px 36px" }}>
            <div className="auth-success-mark"><CheckIcon /></div>
            <h1 className="auth-title" style={{ fontSize: 24, marginTop: 16 }}>You're in.</h1>
            <p className="auth-sub" style={{ marginTop: 6 }}>Loading MSACare PDSP Report…</p>
          </div>
        )}
      </div>
      <div className="auth-below auth-builtby-slot">
        {window.BuiltByRedBitAuth ? <window.BuiltByRedBitAuth /> : null}
      </div>
    </div>
  );
};

window.AuthFlow = AuthFlow;
