// ─── K&N Elite — Login / OTP (unified light) ───

const { useState, useEffect } = React;

function ScreenLogin({ onSuccess, prefillPhone }) {
  const { t } = useI18n();
  const [step, setStep] = useState("phone");
  const [phone, setPhone] = useState(prefillPhone || "+34 ");
  const [code, setCode] = useState(["", "", "", "", "", ""]);
  const [resend, setResend] = useState(60);

  useEffect(() => {
    if (step !== "code") return;
    const id = setInterval(() => setResend(r => Math.max(0, r - 1)), 1000);
    return () => clearInterval(id);
  }, [step]);

  const setDigit = (i, v) => {
    if (!/^\d?$/.test(v)) return;
    const arr = [...code]; arr[i] = v; setCode(arr);
    if (v && i < 5) {
      const next = document.getElementById("d-" + (i + 1));
      next && next.focus();
    }
    if (arr.every(x => x !== "")) setTimeout(() => onSuccess(phone), 400);
  };

  return (
    <div className="page fade" style={{ background: "var(--ivory)" }}>
      <Topbar onNav={window.__nav} current="cabinet" />
      <main style={{
        flex: 1, display: "grid", placeItems: "center", padding: "60px 40px",
      }}>
        <div className="card rise" style={{
          width: "min(520px, 100%)", padding: 56, textAlign: "center",
          background: "var(--paper)",
        }}>
          <BrandMark size={48} />
          <div className="eyebrow" style={{ marginTop: 28 }}>{t("login_sub")}</div>
          <h2 style={{ marginTop: 12, fontSize: 36 }}>{t("login_title")}</h2>

          {step === "phone" ? (
            <>
              <div className="field" style={{ marginTop: 36, textAlign: "left" }}>
                <div className="label">{t("login_phone_label")}</div>
                <input className="input" value={phone} onChange={(e) => setPhone(e.target.value)} autoFocus />
              </div>
              <button className="btn btn-gold btn-lg" style={{ width: "100%", marginTop: 28 }} onClick={() => { setStep("code"); setResend(60); }}>
                {t("login_send_code")} →
              </button>
              <div style={{
                display: "flex", alignItems: "center", gap: 16, margin: "32px 0 24px",
              }}>
                <div style={{ flex: 1, height: 1, background: "var(--ink-10)" }} />
                <span style={{ fontSize: 11, color: "var(--ink-40)", fontFamily: "var(--mono)", letterSpacing: "0.22em", textTransform: "uppercase" }}>{t("login_or")}</span>
                <div style={{ flex: 1, height: 1, background: "var(--ink-10)" }} />
              </div>
              <button className="btn btn-ghost" style={{ width: "100%" }} onClick={() => window.__nav("home")}>
                {t("login_valuate_cta")}
              </button>
            </>
          ) : (
            <>
              <div className="field" style={{ marginTop: 36 }}>
                <div className="label">{t("login_code_label")}</div>
                <div style={{ display: "flex", gap: 10, justifyContent: "center", marginTop: 12 }}>
                  {code.map((d, i) => (
                    <input key={i} id={"d-" + i} value={d} onChange={(e) => setDigit(i, e.target.value)}
                      maxLength={1}
                      style={{
                        width: 54, height: 64, textAlign: "center",
                        fontFamily: "var(--serif)", fontSize: 28, fontWeight: 400,
                        background: "var(--paper)", border: "1px solid var(--ink-10)",
                        transition: "all .25s var(--ease)", borderRadius: 2,
                      }}
                      onFocus={(e) => { e.target.style.borderColor = "var(--gold)"; e.target.style.boxShadow = "var(--sh-gold)"; }}
                      onBlur={(e) => { e.target.style.borderColor = "var(--ink-10)"; e.target.style.boxShadow = "none"; }} />
                  ))}
                </div>
                <div style={{ marginTop: 16, fontSize: 12, color: "var(--ink-40)" }}>{t("login_code_hint")}</div>
              </div>
              <div style={{ marginTop: 28, fontSize: 12, color: "var(--ink-60)" }}>
                {resend > 0 ? `${t("login_resend_in")} ${resend}s` : <a style={{ color: "var(--gold-deep)", cursor: "pointer" }} onClick={() => setResend(60)}>{t("login_resend")}</a>}
              </div>
              <div className="mono" style={{ marginTop: 20, color: "var(--gold-deep)", fontSize: 10 }}>
                {t("login_demo_note")}
              </div>
            </>
          )}
        </div>
      </main>
      <Footer />
    </div>
  );
}

Object.assign(window, { ScreenLogin });
