// mb-auth.jsx — authentication flow (welcome, login, signup, forgot, otp, reset)

const LOGO_SRC = "uploads/logomorarbem2.png";

// Fallback gradients when no slides are configured in the ADM
const AUTH_SLIDES_FALLBACK = [
  { c: ["#2C4E92", "#141d3c"] },
  { c: ["#B97E4F", "#5f3c25"] },
  { c: ["#E2762E", "#8f3a1e"] },
  { c: ["#1C97AC", "#0d4f5e"] },
  { c: ["#C2455B", "#5f1f2c"] },
  { c: ["#3C6E55", "#1d3729"] },
];

function BgCarousel({ band }) {
  const [idx, setIdx] = React.useState(0);
  const [imgSlides, setImgSlides] = React.useState(null); // null = loading

  // Load slides from API
  React.useEffect(() => {
    API.designAssets()
      .then(d => setImgSlides((d.login_slides || []).filter(s => s && s.startsWith("http"))))
      .catch(() => setImgSlides([]));
  }, []);

  const slides = imgSlides && imgSlides.length > 0 ? imgSlides : null;
  const count = slides ? slides.length : AUTH_SLIDES_FALLBACK.length;

  React.useEffect(() => {
    const t = setInterval(() => setIdx(x => (x + 1) % count), 4000);
    return () => clearInterval(t);
  }, [count]);

  return (
    <div style={{ position: "absolute", inset: 0, overflow: "hidden", background: "#11142f" }}>
      {slides
        // Real images from ADM
        ? slides.map((url, i) => (
          <div key={i} style={{ position: "absolute", inset: 0, opacity: i === idx ? 1 : 0, transition: "opacity 1.4s ease" }}>
            <img src={url} alt="" style={{ position: "absolute", inset: 0, width: "100%", height: "100%", objectFit: "cover" }} />
            <div style={{ position: "absolute", inset: 0, background: "linear-gradient(180deg, rgba(13,16,46,.35) 0%, rgba(13,16,46,.15) 40%, rgba(13,16,46,.7) 78%, rgba(13,16,46,.9) 100%)" }} />
          </div>
        ))
        // Gradient fallback while loading or when no slides configured
        : AUTH_SLIDES_FALLBACK.map((s, i) => (
          <div key={i} style={{ position: "absolute", inset: 0, opacity: i === idx ? 1 : 0, transition: "opacity 1.3s ease" }}>
            <div className="mb-ken" style={{ position: "absolute", inset: -24, background: `linear-gradient(135deg, ${s.c[0]}, ${s.c[1]})`, animationPlayState: i === idx ? "running" : "paused" }}>
              <div style={{ position: "absolute", inset: 0, background: "repeating-linear-gradient(135deg, rgba(255,255,255,.05) 0 16px, rgba(0,0,0,.05) 16px 32px)" }} />
            </div>
          </div>
        ))
      }
      <div style={{ position: "absolute", left: 0, right: 0, bottom: band ? 14 : 138, display: "flex", gap: 6, justifyContent: "center", zIndex: 4 }}>
        {Array.from({ length: count }).map((_, i) => (
          <span key={i} style={{ width: i === idx ? 20 : 6, height: 6, borderRadius: 999, background: i === idx ? "#fff" : "rgba(255,255,255,.45)", transition: "all .35s" }} />
        ))}
      </div>
    </div>
  );
}

function AuthInput({ label, value, onChange, placeholder, type = "text", icon, password }) {
  const [show, setShow] = React.useState(false);
  const t = password ? (show ? "text" : "password") : type;
  return (
    <div>
      {label && <div style={{ font: "700 12.5px var(--ui)", color: "var(--text)", marginBottom: 7 }}>{label}</div>}
      <div style={{ position: "relative", display: "flex", alignItems: "center" }}>
        {icon && <span style={{ position: "absolute", left: 13, display: "flex" }}><Icon name={icon} size={19} color="var(--muted)" /></span>}
        <input type={t} value={value} placeholder={placeholder} onChange={e => onChange(e.target.value)}
          style={{ width: "100%", boxSizing: "border-box", border: "1.5px solid var(--line)", borderRadius: 13, padding: icon ? "14px 44px 14px 42px" : "14px 14px", font: "600 14.5px var(--ui)", color: "var(--text)", background: "var(--surface)", outline: "none" }} />
        {password && (
          <button onClick={() => setShow(s => !s)} style={{ position: "absolute", right: 8, background: "none", border: "none", cursor: "pointer", padding: 6, display: "flex" }}>
            <Icon name={show ? "eyeoff" : "eye"} size={19} color="var(--muted)" />
          </button>
        )}
      </div>
    </div>
  );
}

function OtpInput({ value, onChange }) {
  const refs = React.useRef([null, null, null, null]);
  const focus = (i) => refs.current[i] && refs.current[i].focus();

  const set = (i, raw) => {
    const digits = raw.replace(/\D/g, "");
    if (!digits) {
      // apagou — limpa esta posição
      const arr = value.split("");
      arr[i] = "";
      onChange(arr.join("").slice(0, 4));
      return;
    }
    // suporta colar / autocompletar vários dígitos de uma vez
    if (digits.length > 1) {
      const arr = value.split("");
      digits.split("").forEach((d, j) => { if (i + j < 4) arr[i + j] = d; });
      onChange(arr.join("").slice(0, 4));
      const next = Math.min(i + digits.length, 3);
      focus(next);
      return;
    }
    const arr = value.split("");
    arr[i] = digits[0];
    onChange(arr.join("").slice(0, 4));
    if (i < 3) focus(i + 1);
  };

  return (
    <div style={{ display: "flex", gap: 12, justifyContent: "center" }}>
      {[0, 1, 2, 3].map(i => (
        <input key={i} ref={el => refs.current[i] = el}
          inputMode="numeric" maxLength={4} value={value[i] || ""}
          onChange={e => set(i, e.target.value)}
          onKeyDown={e => {
            if (e.key === "Backspace" && !value[i] && i > 0) {
              const arr = value.split(""); arr[i - 1] = "";
              onChange(arr.join("").slice(0, 4));
              focus(i - 1);
            }
          }}
          style={{ width: 56, height: 64, textAlign: "center", border: value[i] ? "1.5px solid var(--accent)" : "1.5px solid var(--line)", borderRadius: 15, font: "800 26px var(--ui)", color: "var(--text)", background: "var(--surface)", outline: "none" }} />
      ))}
    </div>
  );
}

function AuthHeader({ onBack, title, sub }) {
  return (
    <div style={{ padding: "52px 4px 10px" }}>
      {onBack && <IconBtn name="arrowL" onClick={onBack} size={40} bg="var(--surface)" />}
      <h1 style={{ margin: onBack ? "20px 0 0" : "8px 0 0", font: "800 28px var(--ui)", color: "var(--text)", letterSpacing: "-.01em" }}>{title}</h1>
      {sub && <p style={{ font: "500 14px var(--ui)", color: "var(--muted)", lineHeight: 1.5, margin: "8px 0 0" }}>{sub}</p>}
    </div>
  );
}


const Divider = () => (
  <div style={{ display: "flex", alignItems: "center", gap: 12, margin: "4px 0" }}>
    <div style={{ flex: 1, height: 1, background: "var(--line)" }} />
    <span style={{ font: "600 11.5px var(--ui)", color: "var(--muted)" }}>ou</span>
    <div style={{ flex: 1, height: 1, background: "var(--line)" }} />
  </div>
);

function AuthFlow({ onAuthed, onToast, onCancel }) {
  const [screen, setScreen] = React.useState(Auth.isLogged() ? "autologin" : "welcome");
  const [email, setEmail] = React.useState("");
  const [pwd, setPwd] = React.useState("");
  const [name, setName] = React.useState("");
  const [phone, setPhone] = React.useState("");
  const [cpf, setCpf] = React.useState("");
  const [agree, setAgree] = React.useState(false);
  const [otp, setOtp] = React.useState("");
  const [npwd, setNpwd] = React.useState("");
  const [purpose, setPurpose] = React.useState("signup");
  const [loading, setLoading] = React.useState(false);
  const [error, setError] = React.useState("");

  const err = (e) => {
    const status = e?.status;
    let msg = e?.detail || e?.title || "Algo deu errado. Tente novamente.";
    if (status === 409) msg = "E-mail ou CPF já cadastrado. Verifique seus dados ou faça login.";
    if (status === 400 && (msg.includes("OTP") || msg.includes("otp") || msg.includes("invalid")))
      msg = "Código inválido ou expirado. Reenvie um novo código.";
    if (status === 403) msg = "E-mail ou senha incorretos.";
    setError(msg); onToast(msg);
    setLoading(false);
  };

  // Auto-login com token existente
  React.useEffect(() => {
    if (screen === "autologin") {
      API.me.get().then(user => onAuthed(user)).catch(() => {
        Auth.clear(); setScreen("welcome");
      });
    }
  }, []);

  const goOtp = (p) => { setPurpose(p); setOtp(""); setError(""); setScreen("otp"); };

  // ── Welcome ──
  if (screen === "welcome" || screen === "autologin") {
    return (
      <div style={{ position: "absolute", inset: 0, overflow: "hidden" }}>
        <BgCarousel />
        <div style={{ position: "absolute", inset: 0, background: "linear-gradient(180deg, rgba(13,16,46,.5) 0%, rgba(13,16,46,.22) 36%, rgba(13,16,46,.82) 70%, rgba(13,16,46,.96) 100%)" }} />
        <div style={{ position: "absolute", inset: 0, display: "flex", flexDirection: "column", padding: "0 24px 30px" }}>
          {onCancel && (
            <div style={{ paddingTop: "max(52px, env(safe-area-inset-top, 52px))", display: "flex", justifyContent: "flex-end", position: "relative", zIndex: 3 }}>
              <button onClick={onCancel} style={{ background: "rgba(255,255,255,0.18)", border: "none", borderRadius: 999, width: 36, height: 36, display: "flex", alignItems: "center", justifyContent: "center", cursor: "pointer", backdropFilter: "blur(6px)" }}>
                <Icon name="close" size={18} color="#fff" />
              </button>
            </div>
          )}
          <div style={{ flex: 1, display: "flex", flexDirection: "column", alignItems: "center", justifyContent: "center", textAlign: "center", paddingTop: onCancel ? 0 : 30 }}>
            <img src={LOGO_SRC} alt="Morar Bem" style={{ width: 232, filter: "brightness(0) invert(1) drop-shadow(0 4px 20px rgba(0,0,0,.4))" }} />
            <p style={{ font: "500 16px var(--ui)", color: "rgba(255,255,255,.92)", lineHeight: 1.5, margin: "26px 12px 0", maxWidth: 300, textShadow: "0 1px 12px rgba(0,0,0,.45)" }}>
              O guia da sua cidade — descubra parceiros, peça com cashback e cuide do seu lar.
            </p>
          </div>
          {screen === "autologin"
            ? <div style={{ display: "flex", justifyContent: "center", padding: 24 }}><div style={{ width: 32, height: 32, borderRadius: 999, border: "3px solid rgba(255,255,255,.4)", borderTopColor: "#fff", animation: "spin 0.7s linear infinite" }} /></div>
            : <div style={{ display: "flex", flexDirection: "column", gap: 11, position: "relative", zIndex: 2 }}>
                <Btn full onClick={() => setScreen("signup")}>Criar conta</Btn>
                <button onClick={() => setScreen("login")} style={{ height: 52, borderRadius: 15, border: "1.5px solid rgba(255,255,255,.55)", background: "rgba(255,255,255,.08)", backdropFilter: "blur(6px)", WebkitBackdropFilter: "blur(6px)", color: "#fff", cursor: "pointer", font: "650 16px var(--ui)" }}>Já tenho conta</button>
              </div>
          }
          <div style={{ textAlign: "center", font: "500 11.5px var(--ui)", color: "rgba(255,255,255,.62)", marginTop: 16, lineHeight: 1.5 }}>
            Ao continuar você aceita os Termos de uso<br />e a Política de privacidade.
          </div>
        </div>
      </div>
    );
  }

  // ── Login ──
  if (screen === "login") {
    const doLogin = async () => {
      if (!email || !pwd) return;
      setLoading(true); setError("");
      try {
        const { customer, tokens } = await API.auth.login({ email, password: pwd });
        Auth.set(tokens.access_token);
        Auth.setRefresh(tokens.refresh_token);
        onAuthed(customer);
      } catch (e) {
        err(e);
      } finally {
        setLoading(false);
      }
    };
    return (
      <div style={{ position: "absolute", inset: 0, display: "flex", flexDirection: "column", background: "var(--bg)" }}>
        <div style={{ position: "relative", height: 264, flexShrink: 0, overflow: "hidden" }}>
          <BgCarousel band />
          <div style={{ position: "absolute", inset: 0, background: "linear-gradient(180deg, rgba(13,16,46,.45) 0%, rgba(13,16,46,.15) 40%, rgba(13,16,46,.7) 78%, var(--bg) 100%)" }} />
          <div style={{ position: "absolute", top: 52, left: 14, zIndex: 3 }}><IconBtn name="arrowL" onClick={() => setScreen("welcome")} size={40} bg="rgba(255,255,255,.92)" /></div>
          <img src={LOGO_SRC} alt="Morar Bem" style={{ position: "absolute", top: 60, left: "50%", transform: "translateX(-50%)", width: 138, filter: "brightness(0) invert(1) drop-shadow(0 3px 14px rgba(0,0,0,.4))", zIndex: 3 }} />
          <div style={{ position: "absolute", left: 24, right: 24, bottom: 28, zIndex: 3 }}>
            <h1 style={{ margin: 0, font: "800 28px var(--ui)", color: "#fff", textShadow: "0 2px 14px rgba(0,0,0,.4)" }}>Entrar</h1>
            <p style={{ font: "500 13.5px var(--ui)", color: "rgba(255,255,255,.9)", margin: "5px 0 0", textShadow: "0 1px 10px rgba(0,0,0,.4)" }}>Que bom te ver de novo!</p>
          </div>
        </div>
        <div style={{ flex: 1, overflow: "auto", marginTop: -20, borderRadius: "24px 24px 0 0", background: "var(--bg)", padding: "24px 24px 30px", position: "relative", zIndex: 2 }}>
          <div style={{ display: "flex", flexDirection: "column", gap: 14 }}>
            <AuthInput label="E-mail" value={email} onChange={v => { setEmail(v); setError(""); }} placeholder="voce@email.com" icon="mail" />
            <AuthInput label="Senha" value={pwd} onChange={v => { setPwd(v); setError(""); }} placeholder="Sua senha" icon="lock" password />
            {error && <div style={{ font: "600 12.5px var(--ui)", color: "#D4493A", textAlign: "center" }}>{error}</div>}
            <button onClick={() => setScreen("forgot")} style={{ alignSelf: "flex-end", background: "none", border: "none", cursor: "pointer", font: "700 12.5px var(--ui)", color: "var(--accent)", padding: 2 }}>Esqueci a senha</button>
            <Btn full disabled={!email || !pwd || loading} onClick={doLogin} style={{ marginTop: 2 }}>
              {loading ? "Entrando…" : "Entrar"}
            </Btn>
          </div>
          <AuthFooter q="Não tem conta?" a="Criar conta" onClick={() => setScreen("signup")} />
        </div>
      </div>
    );
  }

  // ── Signup ──
  if (screen === "signup") {
    const ok = name && email && phone && cpf && pwd && agree;
    const doSignup = async () => {
      if (!ok) return;
      setLoading(true); setError("");
      try {
        await API.auth.forgot({ email, purpose: "signup" });
        goOtp("signup");
      } catch (e) {
        err(e);
      } finally {
        setLoading(false);
      }
    };
    return (
      <AuthScreen>
        <AuthHeader onBack={() => setScreen("welcome")} title="Criar conta" sub="Leva menos de um minuto e o cashback já começa." />
        <div style={{ display: "flex", flexDirection: "column", gap: 14, marginTop: 8 }}>
          <AuthInput label="Nome completo" value={name} onChange={setName} placeholder="Seu nome" icon="user" />
          <AuthInput label="E-mail" value={email} onChange={setEmail} placeholder="voce@email.com" icon="mail" type="email" />
          <AuthInput label="Telefone / WhatsApp" value={phone} onChange={setPhone} placeholder="(79) 9 0000-0000" icon="phone" />
          <AuthInput label="CPF" value={cpf} onChange={setCpf} placeholder="000.000.000-00" icon="user" />
          <AuthInput label="Senha" value={pwd} onChange={setPwd} placeholder="Crie uma senha" icon="lock" password />
          <button onClick={() => setAgree(a => !a)} style={{ display: "flex", alignItems: "flex-start", gap: 10, background: "none", border: "none", cursor: "pointer", textAlign: "left", padding: "2px 0" }}>
            <span style={{ width: 22, height: 22, borderRadius: 7, flexShrink: 0, marginTop: 1, border: agree ? "none" : "1.5px solid var(--line)", background: agree ? "var(--accent)" : "var(--surface)", display: "flex", alignItems: "center", justifyContent: "center" }}>{agree && <Icon name="check" size={14} color="var(--accent-ink)" sw={3} />}</span>
            <span style={{ font: "500 12.5px var(--ui)", color: "var(--muted)", lineHeight: 1.45 }}>Li e aceito os <b style={{ color: "var(--text)" }}>Termos de uso</b> e a <b style={{ color: "var(--text)" }}>Política de privacidade</b>.</span>
          </button>
          {error && <div style={{ font: "600 12.5px var(--ui)", color: "#D4493A", textAlign: "center" }}>{error}</div>}
          <Btn full disabled={!ok || loading} onClick={doSignup} style={{ marginTop: 2 }}>
            {loading ? "Aguarde…" : "Criar conta"}
          </Btn>
        </div>
        <AuthFooter q="Já tem conta?" a="Entrar" onClick={() => setScreen("login")} />
      </AuthScreen>
    );
  }

  // ── Forgot ──
  if (screen === "forgot") {
    const doForgot = async () => {
      if (!email) return;
      setLoading(true); setError("");
      try {
        await API.auth.forgot({ email });
        goOtp("reset");
      } catch (e) { err(e); }
      finally { setLoading(false); }
    };
    return (
      <AuthScreen>
        <AuthHeader onBack={() => setScreen("login")} title="Esqueceu a senha?" sub="Informe seu e-mail e enviaremos um código para você criar uma nova senha." />
        <div style={{ display: "flex", flexDirection: "column", gap: 14, marginTop: 8 }}>
          <AuthInput label="E-mail" value={email} onChange={setEmail} placeholder="voce@email.com" icon="mail" type="email" />
          <Btn full disabled={!email || loading} onClick={doForgot} style={{ marginTop: 2 }}>
            {loading ? "Enviando…" : "Enviar código"}
          </Btn>
        </div>
      </AuthScreen>
    );
  }

  // ── OTP ──
  if (screen === "otp") {
    const doOtp = async () => {
      if (otp.length < 4) return;
      setLoading(true); setError("");
      let navigated = false;
      try {
        await API.auth.verifyOtp({ email, otp });
        if (purpose === "signup") {
          const { customer, tokens } = await API.auth.register({ name, email, phone, cpf, password: pwd });
          Auth.set(tokens.access_token);
          Auth.setRefresh(tokens.refresh_token);
          navigated = true;
          onToast("Conta criada! Bem-vindo(a)");
          onAuthed(customer);
        } else {
          navigated = true;
          setNpwd(""); setPwd("");
          setScreen("reset");
        }
      } catch (e) {
        err(e);
      } finally {
        if (!navigated) setLoading(false);
      }
    };
    return (
      <AuthScreen>
        <AuthHeader onBack={() => setScreen(purpose === "signup" ? "signup" : "forgot")} title="Verificação" sub={`Enviamos um código de 4 dígitos para ${email || phone || "seu contato"}.`} />
        <div style={{ marginTop: 18 }}>
          <OtpInput value={otp} onChange={setOtp} />
          {error && <div style={{ font: "600 12.5px var(--ui)", color: "#D4493A", textAlign: "center", marginTop: 10 }}>{error}</div>}
          <div style={{ textAlign: "center", marginTop: 14, font: "500 13px var(--ui)", color: "var(--muted)" }}>
            Não recebeu? <button onClick={() => { setError(""); API.auth.forgot({ email, purpose }); onToast("Código reenviado"); }} style={{ background: "none", border: "none", cursor: "pointer", font: "700 13px var(--ui)", color: "var(--accent)" }}>Reenviar</button>
          </div>
          <Btn full disabled={otp.length < 4 || loading} onClick={doOtp} style={{ marginTop: 24 }}>
            {loading ? "Verificando…" : "Confirmar"}
          </Btn>
        </div>
      </AuthScreen>
    );
  }

  // ── Reset ──
  if (screen === "reset") {
    const doReset = async () => {
      if (npwd.length < 6 || npwd !== pwd) return;
      setLoading(true); setError("");
      try {
        await API.auth.reset({ email, otp, password: npwd });
        onToast("Senha alterada com sucesso");
        setScreen("login");
      } catch (e) { err(e); }
    };
    return (
      <AuthScreen>
        <AuthHeader onBack={() => setScreen("login")} title="Nova senha" sub="Crie uma senha nova para acessar sua conta." />
        <div style={{ display: "flex", flexDirection: "column", gap: 14, marginTop: 8 }}>
          <AuthInput label="Nova senha" value={npwd} onChange={setNpwd} placeholder="Mínimo 6 caracteres" icon="lock" password />
          <AuthInput label="Confirmar senha" value={pwd} onChange={setPwd} placeholder="Repita a senha" icon="lock" password />
          {npwd && pwd && npwd !== pwd && <div style={{ font: "600 12px var(--ui)", color: "#D4493A", textAlign: "center" }}>As senhas não coincidem</div>}
          <Btn full disabled={npwd.length < 6 || npwd !== pwd || loading} onClick={doReset} style={{ marginTop: 2 }}>
            {loading ? "Salvando…" : "Salvar nova senha"}
          </Btn>
        </div>
      </AuthScreen>
    );
  }

  return null;
}

function AuthScreen({ children }) {
  return <div style={{ position: "absolute", inset: 0, overflow: "auto", background: "var(--bg)", padding: "0 24px 30px" }}>{children}</div>;
}
function AuthFooter({ q, a, onClick }) {
  return (
    <div style={{ textAlign: "center", padding: "22px 0 6px", font: "500 13.5px var(--ui)", color: "var(--muted)" }}>
      {q} <button onClick={onClick} style={{ background: "none", border: "none", cursor: "pointer", font: "800 13.5px var(--ui)", color: "var(--accent)" }}>{a}</button>
    </div>
  );
}

Object.assign(window, { AuthFlow, AuthInput, OtpInput });
