/* global React, VendusAtoms, supabase */
/* =====================================================
   VendusAuth — autenticação multitenant (Supabase Auth)
   TUDO dentro de um IIFE para NÃO poluir o escopo global
   (estes scripts sem build compartilham o mesmo escopo; sem
   isolamento, nomes como "Field" colidiriam com outras telas).
   Só expomos window.VendusAuth e window.VendusAuthScreen.
===================================================== */
(function () {
  const { I, Btn } = window.VendusAtoms;
  const { useState } = React;

  let _sb = null;
  let _ready = null;

  async function init() {
    if (_sb) return _sb;
    if (!_ready) {
      _ready = (async () => {
        const cfg = await fetch("/api/public-config").then((r) => r.json()).catch(() => ({}));
        if (!window.supabase || !cfg.supabaseUrl || !cfg.supabaseAnonKey) {
          throw new Error("Configuração de login indisponível.");
        }
        _sb = window.supabase.createClient(cfg.supabaseUrl, cfg.supabaseAnonKey, {
          auth: { persistSession: true, autoRefreshToken: true, storage: window.localStorage },
        });
        return _sb;
      })();
    }
    return _ready;
  }

  async function getSession() {
    const sb = await init();
    const { data } = await sb.auth.getSession();
    return data.session || null;
  }
  async function getToken() {
    const s = await getSession();
    return s ? s.access_token : null;
  }
  // Lê/grava a alíquota de imposto do vendedor (em user_metadata)
  async function getImpostoPct() {
    const s = await getSession();
    return Number((s && s.user && s.user.user_metadata && s.user.user_metadata.imposto_pct) || 0) || 0;
  }
  async function setImpostoPct(pct) {
    const sb = await init();
    const n = Number(String(pct).replace(",", ".")) || 0;
    const { error } = await sb.auth.updateUser({ data: { imposto_pct: n } });
    if (error) return { ok: false, error: error.message };
    return { ok: true, imposto_pct: n };
  }
  // Config do "responder sozinho" (em user_metadata)
  async function getAutoResponder() {
    const s = await getSession();
    const c = s && s.user && s.user.user_metadata && s.user.user_metadata.auto_responder;
    return c && typeof c === "object" ? c : { enabled: false, categorias: ["estoque", "caracteristica"], cap_diario: 30 };
  }
  async function setAutoResponder(cfg) {
    const sb = await init();
    const { error } = await sb.auth.updateUser({ data: { auto_responder: cfg } });
    if (error) return { ok: false, error: error.message };
    return { ok: true };
  }
  // Tom da IA (em user_metadata)
  async function getTom() {
    const s = await getSession();
    return (s && s.user && s.user.user_metadata && s.user.user_metadata.tom_ia) || "cordial";
  }
  async function setTom(tom) {
    const sb = await init();
    const { error } = await sb.auth.updateUser({ data: { tom_ia: tom } });
    if (error) return { ok: false, error: error.message };
    return { ok: true };
  }
  // Metas do mês (em user_metadata): { receita, lucro, pedidos }
  async function getMetas() {
    const s = await getSession();
    const m = s && s.user && s.user.user_metadata && s.user.user_metadata.metas;
    return m && typeof m === "object" ? m : { receita: 0, lucro: 0, pedidos: 0 };
  }
  async function setMetas(metas) {
    const sb = await init();
    const { error } = await sb.auth.updateUser({ data: { metas } });
    if (error) return { ok: false, error: error.message };
    return { ok: true };
  }
  async function signIn(email, password) {
    const sb = await init();
    const { data, error } = await sb.auth.signInWithPassword({ email, password });
    if (error) return { ok: false, error: traduz(error.message) };
    return { ok: true, session: data.session };
  }
  async function signUp({ full_name, email, phone, password }) {
    const r = await fetch("/api/auth/signup", {
      method: "POST",
      headers: { "content-type": "application/json" },
      body: JSON.stringify({ full_name, email, phone, password }),
    });
    const d = await r.json().catch(() => ({}));
    if (!r.ok) return { ok: false, error: d.error || "Não consegui criar a conta." };
    return signIn(email, password); // acesso na hora
  }
  async function signOut() {
    const sb = await init();
    await sb.auth.signOut();
  }
  function onAuthChange(cb) {
    init().then((sb) => sb.auth.onAuthStateChange((_e, session) => cb(session)));
  }
  function traduz(m) {
    if (/invalid login credentials/i.test(m)) return "E-mail ou senha incorretos.";
    if (/email not confirmed/i.test(m)) return "E-mail ainda não confirmado.";
    if (/rate limit/i.test(m)) return "Muitas tentativas. Aguarde um momento.";
    return m;
  }
  function initialsOf(name, email) {
    const base = String(name || email || "U").trim();
    const parts = base.split(/\s+/).filter(Boolean);
    if (parts.length >= 2) return (parts[0][0] + parts[1][0]).toUpperCase();
    return base.slice(0, 2).toUpperCase();
  }

  window.VendusAuth = { init, getSession, getToken, signIn, signUp, signOut, onChange: onAuthChange, initialsOf, getImpostoPct, setImpostoPct, getAutoResponder, setAutoResponder, getTom, setTom, getMetas, setMetas };

  /* ---------- Logo ---------- */
  const AuthLogo = ({ size = 56 }) => (
    <svg width={size} height={size} viewBox="0 0 100 100" style={{ display: "block" }} aria-label="Vendus">
      <defs>
        <linearGradient id="authLogoGrad" x1="0" y1="0" x2="1" y2="1">
          <stop offset="0%" stopColor="#FF9248" />
          <stop offset="100%" stopColor="#F74B0A" />
        </linearGradient>
      </defs>
      <circle cx="50" cy="50" r="50" fill="url(#authLogoGrad)" />
      <path d="M22 32 L50 78 L78 32 L63 32 L50 58 L37 32 Z" fill="#fff" stroke="#fff" strokeWidth="4" strokeLinejoin="round" strokeLinecap="round" />
    </svg>
  );

  /* ---------- Campo (nome único p/ não colidir) ---------- */
  const AuthField = ({ label, children }) => (
    <label style={{ display: "block" }}>
      <div style={{ fontSize: 12, color: "var(--fg-2)", fontWeight: 600, marginBottom: 6 }}>{label}</div>
      {children}
    </label>
  );

  /* ---------- Tela de Login / Cadastro ---------- */
  function AuthScreen() {
    const [mode, setMode] = useState("login"); // login | signup
    const [nome, setNome] = useState("");
    const [email, setEmail] = useState("");
    const [cel, setCel] = useState("");
    const [senha, setSenha] = useState("");
    const [showPw, setShowPw] = useState(false);
    const [loading, setLoading] = useState(false);
    const [erro, setErro] = useState("");

    async function submit(e) {
      e.preventDefault();
      setErro("");
      setLoading(true);
      let r;
      if (mode === "login") {
        r = await window.VendusAuth.signIn(email.trim(), senha);
      } else {
        r = await window.VendusAuth.signUp({ full_name: nome.trim(), email: email.trim(), phone: cel.trim(), password: senha });
      }
      setLoading(false);
      if (!r.ok) {
        setErro(r.error || "Algo deu errado.");
        return;
      }
      // sucesso: o listener de auth no App troca para o aplicativo automaticamente.
    }

    const isSignup = mode === "signup";

    return (
      <div style={{ minHeight: "100vh", display: "grid", placeItems: "center", padding: 20, background: "radial-gradient(1200px 600px at 50% -10%, rgba(249,115,22,.12), transparent 60%), var(--bg-app)" }}>
        <div style={{ width: "100%", maxWidth: 400 }}>
          <div style={{ display: "flex", flexDirection: "column", alignItems: "center", marginBottom: 22 }}>
            <AuthLogo size={56} />
            <div className="font-display" style={{ fontWeight: 800, fontSize: 26, marginTop: 12 }}>Vendus</div>
            <div className="text-faint" style={{ fontSize: 12.5, fontFamily: "Space Grotesk", letterSpacing: ".04em" }}>Gestão multicanal · Copiloto de IA</div>
          </div>

          <div className="card" style={{ padding: 24 }}>
            <div className="seg" style={{ width: "100%", marginBottom: 18, display: "flex" }}>
              <button type="button" style={{ flex: 1 }} className={mode === "login" ? "active" : ""} onClick={() => { setMode("login"); setErro(""); }}>Entrar</button>
              <button type="button" style={{ flex: 1 }} className={mode === "signup" ? "active" : ""} onClick={() => { setMode("signup"); setErro(""); }}>Criar conta</button>
            </div>

            <form onSubmit={submit} style={{ display: "flex", flexDirection: "column", gap: 12 }}>
              {isSignup && (
                <AuthField label="Nome completo">
                  <input className="input" value={nome} onChange={(e) => setNome(e.target.value)} placeholder="Seu nome" autoComplete="name" required />
                </AuthField>
              )}
              <AuthField label="E-mail">
                <input className="input" type="email" value={email} onChange={(e) => setEmail(e.target.value)} placeholder="voce@email.com" autoComplete="email" required />
              </AuthField>
              {isSignup && (
                <AuthField label="Celular (com DDD)">
                  <input className="input" value={cel} onChange={(e) => setCel(e.target.value)} placeholder="(11) 90000-0000" autoComplete="tel" inputMode="tel" required />
                </AuthField>
              )}
              <AuthField label="Senha">
                <div style={{ position: "relative" }}>
                  <input className="input" type={showPw ? "text" : "password"} value={senha} onChange={(e) => setSenha(e.target.value)} placeholder={isSignup ? "mínimo 8 caracteres" : "sua senha"} autoComplete={isSignup ? "new-password" : "current-password"} required style={{ paddingRight: 38 }} />
                  <button type="button" onClick={() => setShowPw((v) => !v)} title={showPw ? "Ocultar" : "Mostrar"}
                    style={{ position: "absolute", right: 8, top: "50%", transform: "translateY(-50%)", background: "none", border: 0, color: "var(--fg-3)", cursor: "pointer", padding: 4 }}>
                    <I name={showPw ? "eye-off" : "eye"} size={16} />
                  </button>
                </div>
              </AuthField>

              {erro && (
                <div style={{ display: "flex", gap: 8, alignItems: "flex-start", background: "rgba(239,68,68,.1)", border: "1px solid rgba(239,68,68,.3)", borderRadius: 10, padding: "10px 12px", fontSize: 13 }}>
                  <I name="alert-triangle" size={15} style={{ color: "#FCA5A5", flexShrink: 0, marginTop: 1 }} />
                  <span>{erro}</span>
                </div>
              )}

              <Btn as="button" variant="primary" type="submit" disabled={loading} style={{ width: "100%", justifyContent: "center", marginTop: 4 }}>
                {loading ? "Aguarde…" : isSignup ? "Criar conta e entrar" : "Entrar"}
              </Btn>
            </form>

            <div className="text-faint" style={{ fontSize: 11.5, textAlign: "center", marginTop: 14, lineHeight: 1.5 }}>
              {isSignup
                ? <>Ao criar a conta você concorda com os termos de uso e a política de privacidade.</>
                : <>Não tem conta? <a onClick={() => { setMode("signup"); setErro(""); }} style={{ color: "var(--primary)", cursor: "pointer", fontWeight: 600 }}>Criar agora</a></>}
            </div>
          </div>
        </div>
      </div>
    );
  }

  window.VendusAuthScreen = AuthScreen;
})();
