// 2FA UI — Componentes compartilhados (sócio + admin)

// ── QR Code SVG renderer (sem dependência externa) ──
// Implementa QR code básico via canvas usando uma lib carregada via CDN
// Fallback: mostra o secret pra digitar manualmente

function QrCanvas({ value, size = 220 }) {
  // Renderiza QR via API pública de imagem — não depende de scripts externos
  const url = `https://api.qrserver.com/v1/create-qr-code/?size=${size}x${size}&margin=0&data=${encodeURIComponent(value)}`;
  const [erro, setErro] = React.useState(false);
  return (
    <div style={{ width: size, height: size, display: "grid", placeItems: "center" }}>
      {erro ? (
        <div style={{ width: size, height: size, background: "#f5f5f7", borderRadius: 12, display: "grid", placeItems: "center", color: "#86868b", fontSize: 12, textAlign: "center", padding: 20 }}>
          QR indisponível — use o código abaixo
        </div>
      ) : (
        <img
          src={url}
          alt="QR code para configurar 2FA"
          width={size}
          height={size}
          style={{ borderRadius: 8, display: "block" }}
          onError={() => setErro(true)}
        />
      )}
    </div>
  );
}

// ── Tela de ativação 2FA — 3 passos ──
function TwoFAActivation({ escopo, identificador, nome, onClose, onAtivado }) {
  // escopo: "admin" | "socio"
  // identificador: username (admin) ou código (sócio)
  const [step, setStep] = React.useState(1);
  const [secret, setSecret] = React.useState("");
  const [otpauth, setOtpauth] = React.useState("");
  const [codigo, setCodigo] = React.useState("");
  const [backupCodes, setBackupCodes] = React.useState([]);
  const [erro, setErro] = React.useState(null);
  const [busy, setBusy] = React.useState(false);

  // Step 1 → 2: gerar secret
  const iniciar = async () => {
    setErro(null); setBusy(true);
    try {
      if (window.IKIGAI_API_ENABLED) {
        const fn = escopo === "admin" ? IkigaiAPI.ativar2FAAdmin : IkigaiAPI.ativar2FA;
        const res = await fn();
        setSecret(res.secret);
        // O QR vem como data URL; usamos otpauth aqui pra renderizar localmente também
        setOtpauth(IkigaiTOTP.otpauthURL({ secret: res.secret, label: identificador, issuer: "Ikigai Dojô" }));
      } else {
        // mock: gera tudo localmente
        const s = IkigaiTOTP.gerarSecret();
        setSecret(s);
        setOtpauth(IkigaiTOTP.otpauthURL({ secret: s, label: identificador, issuer: "Ikigai Dojô" }));
      }
      setStep(2);
    } catch (e) { setErro("Falha ao gerar código. Tente novamente."); }
    finally { setBusy(false); }
  };

  // Step 2 → 3: confirmar com primeiro código
  const confirmar = async () => {
    setErro(null); setBusy(true);
    try {
      if (window.IKIGAI_API_ENABLED) {
        const fn = escopo === "admin" ? IkigaiAPI.confirmar2FAAdmin : IkigaiAPI.confirmar2FA;
        const res = await fn(codigo);
        setBackupCodes(res.backupCodes || []);
      } else {
        // mock: validar localmente
        const ok = await IkigaiTOTP.verificarTOTP(secret, codigo);
        if (!ok) { setErro("Código inválido. Verifique o app e tente novamente."); setBusy(false); return; }
        const codes = IkigaiTOTP.gerarBackupCodes();
        setBackupCodes(codes);
        IkigaiTOTP.Storage.set(escopo, identificador, { secret, ativo: true, backupCodes: codes });
      }
      setStep(3);
    } catch (e) {
      setErro(e.data?.error === "invalid_code" ? "Código inválido." : "Falha ao confirmar.");
    } finally { setBusy(false); }
  };

  const finalizar = () => { onAtivado && onAtivado(); onClose && onClose(); };

  return (
    <div className="as-modal-bg" onClick={(e) => { if (step === 3) finalizar(); else onClose && onClose(); }}>
      <div className="as-modal" onClick={(e) => e.stopPropagation()} style={{ maxWidth: 560 }}>
        <span className="as-modal-x" onClick={onClose}>✕</span>
        <div className="as-modal-h">
          <h3>Ativar autenticação em 2 fatores</h3>
          <p>Passo {step} de 3 · {step === 1 ? "Como funciona" : step === 2 ? "Conecte o aplicativo" : "Guarde os códigos"}</p>
        </div>

        {step === 1 && (
          <div className="as-modal-body">
            <p style={{ fontSize: 14.5, color: "var(--k-ink-2)", lineHeight: 1.55, marginBottom: 16 }}>
              A autenticação em 2 fatores adiciona uma camada extra de segurança: além da sua senha, você precisará informar um código de 6 dígitos gerado por um aplicativo no celular.
            </p>
            <div style={{ background: "#f5f5f7", borderRadius: 12, padding: 16, marginBottom: 16 }}>
              <p style={{ fontSize: 12, color: "var(--k-ink-3)", textTransform: "uppercase", letterSpacing: 0.04, fontWeight: 600, marginBottom: 8 }}>Apps compatíveis</p>
              <p style={{ fontSize: 13, color: "var(--k-ink-2)", lineHeight: 1.5 }}>
                Google Authenticator · Microsoft Authenticator · Authy · 1Password · qualquer app TOTP padrão (RFC 6238).
              </p>
            </div>
            <p style={{ fontSize: 13, color: "var(--k-ink-3)", marginBottom: 6 }}>Tenha um desses apps instalado no celular antes de continuar.</p>
            {erro && <div className="as-2fa-erro">{erro}</div>}
            <div style={{ display: "flex", justifyContent: "flex-end", gap: 8, marginTop: 14 }}>
              <button className="k-btn k-btn-light" onClick={onClose}>Cancelar</button>
              <button className="k-btn k-btn-primary" onClick={iniciar} disabled={busy}>{busy ? "Gerando..." : "Tenho o app, continuar"}</button>
            </div>
          </div>
        )}

        {step === 2 && (
          <div className="as-modal-body">
            <p style={{ fontSize: 14, color: "var(--k-ink-2)", marginBottom: 18 }}>
              <strong>1.</strong> Abra seu app autenticador → "Adicionar conta" → <strong>Escanear QR code</strong>.
            </p>
            <div style={{ display: "flex", justifyContent: "center", marginBottom: 18 }}>
              <div style={{ padding: 12, background: "#fff", border: "1px solid var(--k-line)", borderRadius: 14 }}>
                <QrCanvas value={otpauth} size={220} />
              </div>
            </div>
            <details style={{ marginBottom: 16, fontSize: 13 }}>
              <summary style={{ cursor: "pointer", color: "var(--k-blue)" }}>Não consigo escanear, mostrar o código</summary>
              <div style={{ marginTop: 10, padding: 12, background: "#f5f5f7", borderRadius: 8, fontFamily: "monospace", fontSize: 14, letterSpacing: 1, textAlign: "center", color: "var(--k-ink)" }}>
                {secret.match(/.{1,4}/g)?.join(" ")}
              </div>
              <p style={{ fontSize: 12, color: "var(--k-ink-3)", marginTop: 8 }}>Adicione manualmente esse código no app.</p>
            </details>
            <p style={{ fontSize: 14, color: "var(--k-ink-2)", marginBottom: 8 }}>
              <strong>2.</strong> Digite o código de 6 dígitos que o app está mostrando:
            </p>
            <input
              type="text" inputMode="numeric" pattern="[0-9]{6}" maxLength={7}
              value={codigo} onChange={(e) => setCodigo(e.target.value.replace(/[^0-9]/g, ""))}
              placeholder="000000"
              style={{
                width: "100%", padding: "14px 16px", fontSize: 22, fontFamily: "monospace",
                letterSpacing: 8, textAlign: "center",
                border: "1px solid var(--k-line)", borderRadius: 10, outline: "none",
              }}
              autoFocus
            />
            {erro && <div className="as-2fa-erro">{erro}</div>}
            <div style={{ display: "flex", justifyContent: "space-between", gap: 8, marginTop: 16 }}>
              <button className="k-btn k-btn-light" onClick={() => setStep(1)}>‹ Voltar</button>
              <button className="k-btn k-btn-primary" onClick={confirmar} disabled={busy || codigo.length !== 6}>{busy ? "Verificando..." : "Verificar e ativar"}</button>
            </div>
          </div>
        )}

        {step === 3 && (
          <div className="as-modal-body">
            <div style={{ background: "rgba(45,160,106,0.10)", border: "1px solid rgba(45,160,106,0.25)", borderRadius: 12, padding: 14, marginBottom: 16, display: "flex", alignItems: "center", gap: 12 }}>
              <div style={{ fontSize: 22 }}>✓</div>
              <div>
                <div style={{ fontWeight: 600, color: "#1f7a4d", fontSize: 14 }}>2FA ativado com sucesso!</div>
                <div style={{ fontSize: 12, color: "#1f7a4d", opacity: 0.8 }}>A partir de agora, o código será pedido a cada login.</div>
              </div>
            </div>
            <p style={{ fontSize: 14, fontWeight: 600, color: "var(--k-ink)", marginBottom: 6 }}>Códigos de backup</p>
            <p style={{ fontSize: 13, color: "var(--k-ink-3)", marginBottom: 12, lineHeight: 1.5 }}>
              Guarde estes 10 códigos num lugar seguro. Cada um funciona <strong>uma única vez</strong> caso você perca o celular.
            </p>
            <div style={{ background: "#f5f5f7", border: "1px dashed var(--k-line)", borderRadius: 12, padding: 16, fontFamily: "monospace", fontSize: 14, display: "grid", gridTemplateColumns: "repeat(2, 1fr)", gap: 6, marginBottom: 12 }}>
              {backupCodes.map((c, i) => <span key={i} style={{ color: "var(--k-ink)" }}>{c}</span>)}
            </div>
            <div style={{ display: "flex", gap: 8, marginBottom: 14 }}>
              <button className="k-btn k-btn-light" style={{ flex: 1 }} onClick={() => {
                navigator.clipboard?.writeText(backupCodes.join("\n"));
              }}>Copiar todos</button>
              <button className="k-btn k-btn-light" style={{ flex: 1 }} onClick={() => {
                const txt = `Códigos de backup 2FA — Ikigai\nUsuário: ${nome || identificador}\nData: ${new Date().toLocaleString("pt-BR")}\n\n` + backupCodes.join("\n");
                const blob = new Blob([txt], { type: "text/plain" });
                const url = URL.createObjectURL(blob);
                const a = document.createElement("a");
                a.href = url; a.download = `ikigai-backup-${identificador}.txt`;
                a.click(); URL.revokeObjectURL(url);
              }}>Baixar .txt</button>
            </div>
            <div style={{ display: "flex", justifyContent: "flex-end", marginTop: 8 }}>
              <button className="k-btn k-btn-primary" onClick={finalizar}>Salvei, finalizar</button>
            </div>
          </div>
        )}
      </div>
    </div>
  );
}

// ── Tela de verificação 2FA durante o login ──
function TwoFAVerify({ escopo, tempToken, secret, identificador, emailMasked, onSucesso, onCancelar }) {
  const [codigo, setCodigo] = React.useState("");
  const [tipo, setTipo] = React.useState("totp"); // totp | backup | email
  const [erro, setErro] = React.useState(null);
  const [busy, setBusy] = React.useState(false);
  const [emailEnviado, setEmailEnviado] = React.useState(false);

  const verificar = async () => {
    setErro(null); setBusy(true);
    try {
      if (window.IKIGAI_API_ENABLED) {
        const fn = escopo === "admin" ? IkigaiAPI.loginAdmin2FA : IkigaiAPI.login2FA;
        const user = await fn(tempToken, codigo, tipo);
        onSucesso(user);
      } else {
        // mock: validar com secret/backup local
        const stored = IkigaiTOTP.Storage.get(escopo, identificador);
        if (!stored) { setErro("Sessão expirada."); setBusy(false); return; }
        let ok = false;
        if (tipo === "totp") ok = await IkigaiTOTP.verificarTOTP(stored.secret, codigo);
        else if (tipo === "backup") {
          const idx = stored.backupCodes.indexOf(codigo.toUpperCase().trim());
          if (idx >= 0) {
            stored.backupCodes.splice(idx, 1);
            IkigaiTOTP.Storage.set(escopo, identificador, stored);
            ok = true;
          }
        } else if (tipo === "email") {
          ok = codigo === (stored.lastEmailOtp || "");
        }
        if (!ok) { setErro("Código inválido. Tente novamente."); setBusy(false); return; }
        onSucesso(null); // mock — o caller resolve o user
      }
    } catch (e) {
      setErro(e.data?.error === "invalid_2fa_code" ? "Código inválido." : "Falha ao verificar.");
    } finally { setBusy(false); }
  };

  const enviarEmail = async () => {
    setBusy(true);
    try {
      if (window.IKIGAI_API_ENABLED) {
        const fn = escopo === "admin" ? IkigaiAPI.enviarOtpEmailAdmin : IkigaiAPI.enviarOtpEmailSocio;
        await fn(tempToken);
      } else {
        const otp = String(Math.floor(100000 + Math.random() * 900000));
        const stored = IkigaiTOTP.Storage.get(escopo, identificador) || {};
        stored.lastEmailOtp = otp;
        IkigaiTOTP.Storage.set(escopo, identificador, stored);
        console.log("📧 [DEMO] OTP por e-mail:", otp);
        alert(`[Modo demo] Seu código por e-mail seria: ${otp}`);
      }
      setEmailEnviado(true);
      setTipo("email");
      setCodigo("");
    } catch { setErro("Falha ao enviar e-mail."); }
    finally { setBusy(false); }
  };

  return (
    <div style={{ background: "#fff", borderRadius: 18, padding: "28px 32px", maxWidth: 420, margin: "0 auto", boxShadow: "0 24px 60px rgba(0,0,0,0.08)" }}>
      <div style={{ marginBottom: 6, fontSize: 12, color: "var(--k-ink-3)", textTransform: "uppercase", letterSpacing: 0.06, fontWeight: 600 }}>
        Passo 2 de 2 · Verificação
      </div>
      <h2 style={{ fontSize: 22, fontWeight: 600, color: "var(--k-ink)", marginBottom: 6 }}>
        {tipo === "totp" ? "Código do aplicativo" : tipo === "backup" ? "Código de backup" : "Código enviado por e-mail"}
      </h2>
      <p style={{ fontSize: 13.5, color: "var(--k-ink-3)", marginBottom: 18 }}>
        {tipo === "totp" && "Abra seu app autenticador e digite o código de 6 dígitos."}
        {tipo === "backup" && "Digite um dos códigos de backup salvos quando você ativou o 2FA."}
        {tipo === "email" && `Enviamos um código para ${emailMasked || "seu e-mail"}. Verifique sua caixa de entrada.`}
      </p>

      <input
        type="text" inputMode={tipo === "backup" ? "text" : "numeric"}
        value={codigo} onChange={(e) => setCodigo(tipo === "backup" ? e.target.value.toUpperCase() : e.target.value.replace(/[^0-9]/g, ""))}
        placeholder={tipo === "backup" ? "XXXX-XXXX" : "000000"}
        maxLength={tipo === "backup" ? 9 : 6}
        style={{
          width: "100%", padding: "14px 16px", fontSize: 20, fontFamily: "monospace",
          letterSpacing: tipo === "backup" ? 2 : 8, textAlign: "center",
          border: "1px solid var(--k-line)", borderRadius: 10, outline: "none", marginBottom: 12,
        }}
        autoFocus
        onKeyDown={(e) => e.key === "Enter" && codigo.length >= 6 && verificar()}
      />

      {erro && <div className="as-2fa-erro">{erro}</div>}

      <button className="k-btn k-btn-primary" style={{ width: "100%", marginBottom: 10 }} onClick={verificar} disabled={busy || codigo.length < 6}>
        {busy ? "Verificando..." : "Verificar e entrar"}
      </button>

      <div style={{ display: "flex", flexDirection: "column", gap: 6, marginTop: 14, paddingTop: 14, borderTop: "1px solid var(--k-line-soft)" }}>
        {tipo !== "totp" && <button type="button" onClick={() => { setTipo("totp"); setCodigo(""); setErro(null); }} style={{ background: "none", border: "none", color: "var(--k-blue)", fontSize: 13, cursor: "pointer", padding: 4, textAlign: "left", fontFamily: "inherit" }}>‹ Usar app autenticador</button>}
        {tipo !== "backup" && <button type="button" onClick={() => { setTipo("backup"); setCodigo(""); setErro(null); }} style={{ background: "none", border: "none", color: "var(--k-blue)", fontSize: 13, cursor: "pointer", padding: 4, textAlign: "left", fontFamily: "inherit" }}>Usar código de backup</button>}
        {tipo !== "email" && <button type="button" onClick={enviarEmail} disabled={busy} style={{ background: "none", border: "none", color: "var(--k-blue)", fontSize: 13, cursor: "pointer", padding: 4, textAlign: "left", fontFamily: "inherit" }}>{emailEnviado ? "Reenviar código por e-mail" : "Enviar código por e-mail"}</button>}
        <button type="button" onClick={onCancelar} style={{ background: "none", border: "none", color: "var(--k-ink-3)", fontSize: 13, cursor: "pointer", padding: 4, textAlign: "left", fontFamily: "inherit", marginTop: 4 }}>‹ Cancelar e voltar</button>
      </div>
    </div>
  );
}

Object.assign(window, { TwoFAActivation, TwoFAVerify, QrCanvas });
