// Yomee — Identity Validation Screen
// Second onboarding step. 6-digit OTP, 60s resend, max 3 resends.
// Uses OnboardingHeader from OnboardingShared.jsx; PrimaryButton from Shared.jsx
/* global React, OnboardingHeader, PrimaryButton */

const { useState: useStateIV, useEffect: useEffectIV, useRef: useRefIV } = React;

function IdentityValidationScreen({ onBack, onContinue, email = "tu email" }) {
  const [code, setCode] = useStateIV(["", "", "", "", "", ""]);
  const [error, setError] = useStateIV("");
  const [secondsLeft, setSecondsLeft] = useStateIV(60);
  const [resendCount, setResendCount] = useStateIV(0);
  const [info, setInfo] = useStateIV("");
  const inputs = useRefIV([]);

  useEffectIV(() => {
    if (secondsLeft <= 0) return;
    const t = setTimeout(() => setSecondsLeft((s) => s - 1), 1000);
    return () => clearTimeout(t);
  }, [secondsLeft]);

  const focusBox = (i) => {
    if (i < 0 || i > 5) return;
    inputs.current[i]?.focus();
  };

  const setDigit = (i, v) => {
    const digit = v.replace(/[^\d]/g, "").slice(-1);
    setCode((c) => {
      const next = [...c];
      next[i] = digit;
      return next;
    });
    setError("");
    if (digit && i < 5) focusBox(i + 1);
  };

  const onKey = (i, e) => {
    if (e.key === "Backspace" && !code[i] && i > 0) focusBox(i - 1);
    if (e.key === "ArrowLeft") focusBox(i - 1);
    if (e.key === "ArrowRight") focusBox(i + 1);
  };

  const onPaste = (e) => {
    const txt = (e.clipboardData?.getData("text") || "")
      .replace(/[^\d]/g, "")
      .slice(0, 6);
    if (!txt) return;
    e.preventDefault();
    const next = ["", "", "", "", "", ""];
    for (let i = 0; i < txt.length; i++) next[i] = txt[i];
    setCode(next);
    focusBox(Math.min(txt.length, 5));
  };

  const codeStr = code.join("");
  const filled = codeStr.length === 6;

  const submit = () => {
    if (!filled) {
      setError("Ingresa los 6 dígitos del código.");
      return;
    }
    if (codeStr === "000000") {
      setError("El código no es válido. Inténtalo de nuevo.");
      return;
    }
    onContinue();
  };

  const resend = () => {
    if (secondsLeft > 0 || resendCount >= 3) return;
    setResendCount((n) => n + 1);
    setSecondsLeft(60);
    setCode(["", "", "", "", "", ""]);
    setError("");
    if (resendCount + 1 >= 3) {
      setInfo(
        "Reenviamos tu código por última vez. Si no llega, revisa tu correo no deseado.",
      );
    } else {
      setInfo("Te enviamos un nuevo código a tu correo.");
    }
    focusBox(0);
    setTimeout(() => setInfo(""), 4500);
  };

  const fmtTimer = () => {
    const m = Math.floor(secondsLeft / 60);
    const s = String(secondsLeft % 60).padStart(2, "0");
    return `${m}:${s}`;
  };

  const renderBox = (i) => (
    <input
      key={i}
      ref={(el) => (inputs.current[i] = el)}
      type="text"
      inputMode="numeric"
      maxLength={1}
      value={code[i]}
      onChange={(e) => setDigit(i, e.target.value)}
      onKeyDown={(e) => onKey(i, e)}
      onPaste={onPaste}
      aria-label={`Dígito ${i + 1}`}
      style={{
        width: 44,
        height: 56,
        borderRadius: 14,
        border: error
          ? "1.5px solid var(--yo-coral)"
          : code[i]
            ? "1.5px solid var(--yo-ink)"
            : "1.5px solid var(--yo-ink-200, rgba(20,32,28,0.22))",
        background: "var(--yo-surface)",
        textAlign: "center",
        fontFamily: "var(--font-mono)",
        fontSize: 22,
        fontWeight: 500,
        color: "var(--yo-ink)",
        outline: "none",
        transition: "border-color 140ms ease",
      }}
    />
  );

  return (
    <div
      style={{
        position: "relative",
        width: "100%",
        height: "100%",
        background: "var(--yo-bg)",
        display: "flex",
        flexDirection: "column",
      }}
    >
      <OnboardingHeader onBack={onBack} progress={0.32} screenKey="otp" />

      <div
        style={{
          flex: 1,
          padding: "180px 24px 28px",
          display: "flex",
          flexDirection: "column",
          minHeight: 0,
        }}
      >
        <h1
          style={{
            margin: 0,
            fontFamily: "var(--font-mono)",
            fontWeight: 500,
            fontSize: 26,
            lineHeight: "34px",
            letterSpacing: "0.005em",
            color: "var(--yo-ink)",
          }}
        >
          Ahora confirma
          <br />
          tu cuenta
        </h1>
        <p
          style={{
            margin: "10px 0 32px",
            fontFamily: "var(--font-body)",
            fontSize: 15,
            lineHeight: "22px",
            color: "var(--yo-ink-700, rgba(20,32,28,0.72))",
          }}
        >
          Ingresa el código de 6 dígitos que enviamos a {email}
        </p>

        <div
          style={{
            display: "flex",
            alignItems: "center",
            justifyContent: "space-between",
            gap: 6,
            marginBottom: 8,
          }}
        >
          {renderBox(0)}
          {renderBox(1)}
          {renderBox(2)}
          <span
            aria-hidden
            style={{
              width: 14,
              height: 2,
              background: "var(--yo-ink)",
              borderRadius: 2,
              flex: "0 0 auto",
            }}
          />
          {renderBox(3)}
          {renderBox(4)}
          {renderBox(5)}
        </div>

        {error && (
          <div
            role="alert"
            style={{
              fontFamily: "var(--font-body)",
              fontSize: 13,
              color: "var(--yo-coral)",
              marginTop: 6,
            }}
          >
            {error}
          </div>
        )}

        <div style={{ height: 28 }} />

        <PrimaryButton onClick={submit} disabled={!filled}>
          Continuar
        </PrimaryButton>

        <div
          style={{
            marginTop: 18,
            textAlign: "center",
            fontFamily: "var(--font-body)",
            fontSize: 14,
            color: "var(--yo-ink-700, rgba(20,32,28,0.72))",
          }}
        >
          {secondsLeft > 0 ? (
            <>Reenviar código en {fmtTimer()}</>
          ) : resendCount >= 3 ? (
            <>Has alcanzado el máximo de reenvíos.</>
          ) : (
            <button
              onClick={resend}
              style={{
                background: "transparent",
                border: "none",
                padding: 0,
                cursor: "pointer",
                fontFamily: "var(--font-body)",
                fontSize: 14,
                fontWeight: 600,
                color: "var(--yo-ink)",
                textDecoration: "underline",
                textUnderlineOffset: 4,
              }}
            >
              Reenviar código
              {resendCount > 0 && ` (${3 - resendCount} restantes)`}
            </button>
          )}
        </div>

        {info && (
          <div
            role="status"
            style={{
              marginTop: 14,
              textAlign: "center",
              fontFamily: "var(--font-body)",
              fontSize: 13,
              color: "var(--yo-forest-700, var(--yo-ink))",
            }}
          >
            {info}
          </div>
        )}
      </div>
    </div>
  );
}

window.IdentityValidationScreen = IdentityValidationScreen;
