/* ============================================================
   AfricaMart — Registration & Login (Supabase Auth)
   ============================================================ */
function AuthPage({ nav, params, onAuth, showToast }) {
  const [mode, setMode] = useState(params.mode || "login");
  const [role, setRole] = useState(params.role || "buyer");
  const roleLocked = !!params.role; // came from a role-specific entry point (e.g. "Sell on AfricaMart")

  // Form fields
  const [email,    setEmail]    = useState("");
  const [password, setPassword] = useState("");
  const [name,     setName]     = useState("");
  const [company,  setCompany]  = useState("");
  const [country,  setCountry]  = useState("");
  const [phone,    setPhone]    = useState("");

  // UI state
  const [loading,   setLoading]   = useState(false);
  const [error,     setError]     = useState("");
  const [confirmed, setConfirmed] = useState(false); // email sent
  const [resetSent, setResetSent] = useState(false); // password reset email sent

  // Cloudflare Turnstile (gates login / register / forgot-password —
  // Supabase's CAPTCHA protection is global once enabled in the dashboard)
  const [turnstileToken, setTurnstileToken] = useState("");
  const turnstileRef = useRef(null);
  const widgetIdRef = useRef(null);

  useEffect(() => {
    if (params.mode) setMode(params.mode);
    if (params.role) setRole(params.role);
  }, [params.mode, params.role]);

  // Render the Cloudflare Turnstile widget into whichever form is currently
  // visible (login/register share one form, forgot-password has its own;
  // "reset" needs no widget since updateUser isn't captcha-gated).
  useEffect(() => {
    if (window.turnstile && widgetIdRef.current != null) {
      window.turnstile.remove(widgetIdRef.current);
      widgetIdRef.current = null;
    }
    setTurnstileToken("");

    if (mode === "reset") return;

    let cancelled = false;
    let timer = null;
    const tryRender = () => {
      if (cancelled) return;
      if (!window.turnstile || !turnstileRef.current) {
        timer = setTimeout(tryRender, 200);
        return;
      }
      widgetIdRef.current = window.turnstile.render(turnstileRef.current, {
        sitekey: window.AM_CONFIG.TURNSTILE_SITE_KEY,
        callback: token => setTurnstileToken(token),
        "expired-callback": () => setTurnstileToken(""),
        "error-callback": () => setTurnstileToken(""),
      });
    };
    tryRender();
    return () => {
      cancelled = true;
      if (timer) clearTimeout(timer);
      if (window.turnstile && widgetIdRef.current != null) {
        window.turnstile.remove(widgetIdRef.current);
        widgetIdRef.current = null;
      }
    };
  }, [mode]);

  const clearError = () => setError("");

  // ── Helpers ─────────────────────────────────────────────────

  async function afterSignIn(user, extraMeta = {}) {
    const auth = DB.auth.buildAuthState(user);
    // Ensure buyer or supplier row exists
    try {
      if (auth.role === "supplier") {
        await DB.auth.ensureSupplierRecord(user, extraMeta);
      } else {
        await DB.auth.ensureBuyerRecord(user, extraMeta);
      }
    } catch (e) {
      // Non-fatal — row may already exist or RLS is pending email confirm
      console.warn("[AfricaMart] Could not create profile row:", e.message);
    }
    onAuth(auth);
    nav("dashboard", { role: auth.role });
    showToast("Welcome" + (auth.name ? ", " + auth.name.split(" ")[0] : "") + "!");
  }

  // ── Email / Password Login ───────────────────────────────────

  async function handleLogin(e) {
    e.preventDefault();
    if (!window.supabaseClient) return showToast("Supabase not configured");
    if (!turnstileToken) {
      setError("Please complete the verification check below.");
      return;
    }
    setLoading(true); setError("");
    try {
      const { user } = await DB.auth.signIn(email, password, turnstileToken);
      await afterSignIn(user);
    } catch (err) {
      setError(friendlyError(err.message));
      if (window.turnstile && widgetIdRef.current != null) {
        window.turnstile.reset(widgetIdRef.current);
        setTurnstileToken("");
      }
    } finally {
      setLoading(false);
    }
  }

  // ── Email / Password Register ────────────────────────────────

  async function handleRegister(e) {
    e.preventDefault();
    if (!window.supabaseClient) return showToast("Supabase not configured");
    if (!turnstileToken) {
      setError("Please complete the verification check below.");
      return;
    }
    setLoading(true); setError("");
    try {
      const meta = { role, name, company, country_code: country, phone };
      const { user, session } = await DB.auth.signUp(email, password, meta, turnstileToken);

      if (session) {
        // Email confirmation disabled — user is immediately signed in
        await afterSignIn(user, { company, country_code: country, phone });
      } else {
        // Email confirmation required
        setConfirmed(true);
        showToast("Check your email to verify your account");
      }
    } catch (err) {
      setError(friendlyError(err.message));
      if (window.turnstile && widgetIdRef.current != null) {
        window.turnstile.reset(widgetIdRef.current);
        setTurnstileToken("");
      }
    } finally {
      setLoading(false);
    }
  }

  // ── Forgot / reset password ──────────────────────────────────

  async function handleForgotPassword(e) {
    e.preventDefault();
    if (!window.supabaseClient) return showToast("Supabase not configured");
    if (!turnstileToken) {
      setError("Please complete the verification check below.");
      return;
    }
    setLoading(true); setError("");
    try {
      await DB.auth.resetPasswordForEmail(email, turnstileToken);
      setResetSent(true);
    } catch (err) {
      setError(friendlyError(err.message));
      if (window.turnstile && widgetIdRef.current != null) {
        window.turnstile.reset(widgetIdRef.current);
        setTurnstileToken("");
      }
    } finally {
      setLoading(false);
    }
  }

  async function handleResetPassword(e) {
    e.preventDefault();
    if (!window.supabaseClient) return showToast("Supabase not configured");
    setLoading(true); setError("");
    try {
      await DB.auth.updateUser({ password });
      showToast("Password updated");
      const session = await DB.auth.getSession();
      if (session?.user) await afterSignIn(session.user);
      else nav("auth", { mode: "login" });
    } catch (err) {
      setError(friendlyError(err.message));
    } finally {
      setLoading(false);
    }
  }

  // ── Google OAuth ─────────────────────────────────────────────

  async function handleGoogle() {
    if (!window.supabaseClient) return showToast("Supabase not configured");
    setLoading(true); setError("");
    try {
      await DB.auth.signInWithGoogle();
      // Page will redirect — Supabase handles the return
    } catch (err) {
      setError(friendlyError(err.message));
      setLoading(false);
    }
  }

  // ── Error messages ───────────────────────────────────────────

  function friendlyError(msg) {
    if (!msg) return "Something went wrong. Please try again.";
    if (msg.includes("Invalid login credentials")) return "Incorrect email or password.";
    if (msg.includes("Email not confirmed"))        return "Please verify your email before logging in.";
    if (msg.includes("User already registered"))    return "An account with this email already exists.";
    if (msg.includes("Password should be"))         return "Password must be at least 6 characters.";
    if (msg.includes("Password is known to be weak") || msg.includes("pwned")) return "This password has appeared in a known data breach. Please choose a different, stronger password.";
    if (msg.includes("rate limit") || msg.includes("security purposes")) return "Too many attempts. Please wait a moment and try again.";
    return msg;
  }

  // ── Email-sent confirmation screen ───────────────────────────

  if (confirmed) {
    return (
      <div className="route-anim" style={{ display: "flex", alignItems: "center", justifyContent: "center", minHeight: "calc(100vh - var(--nav-h))", padding: 24, background: "var(--paper)" }}>
        <div style={{ textAlign: "center", maxWidth: 460 }}>
          <div style={{ width: 72, height: 72, borderRadius: "50%", background: "var(--green-50)", color: "var(--green-600)", display: "flex", alignItems: "center", justifyContent: "center", margin: "0 auto 24px" }}>
            <Icon name="mail-check" size={32} />
          </div>
          <h2 style={{ fontSize: 26 }}>Check your email</h2>
          <p className="muted" style={{ fontSize: 15, marginTop: 12, lineHeight: 1.6 }}>
            We sent a verification link to <strong>{email}</strong>. Click it to activate your account.
          </p>
          <button className="btn btn-gold btn-block btn-lg" style={{ marginTop: 28 }} onClick={() => { setConfirmed(false); setMode("login"); }}>
            Back to log in
          </button>
        </div>
      </div>
    );
  }

  // ── Reset-link-sent confirmation screen ──────────────────────

  if (resetSent) {
    return (
      <div className="route-anim" style={{ display: "flex", alignItems: "center", justifyContent: "center", minHeight: "calc(100vh - var(--nav-h))", padding: 24, background: "var(--paper)" }}>
        <div style={{ textAlign: "center", maxWidth: 460 }}>
          <div style={{ width: 72, height: 72, borderRadius: "50%", background: "var(--green-50)", color: "var(--green-600)", display: "flex", alignItems: "center", justifyContent: "center", margin: "0 auto 24px" }}>
            <Icon name="mail-check" size={32} />
          </div>
          <h2 style={{ fontSize: 26 }}>Check your email</h2>
          <p className="muted" style={{ fontSize: 15, marginTop: 12, lineHeight: 1.6 }}>
            If an account exists for <strong>{email}</strong>, we've sent a link to reset your password.
          </p>
          <button className="btn btn-gold btn-block btn-lg" style={{ marginTop: 28 }} onClick={() => { setResetSent(false); setMode("login"); }}>
            Back to log in
          </button>
        </div>
      </div>
    );
  }

  // ── Forgot password form ──────────────────────────────────────

  if (mode === "forgot") {
    return (
      <div className="route-anim" style={{ display: "flex", alignItems: "center", justifyContent: "center", minHeight: "calc(100vh - var(--nav-h))", padding: 24, background: "var(--paper)" }}>
        <form onSubmit={handleForgotPassword} style={{ width: "min(420px, 100%)" }}>
          <h1 style={{ fontSize: 24, marginBottom: 6 }}>Reset your password</h1>
          <p className="muted" style={{ fontSize: 14, marginBottom: 20 }}>Enter your email and we'll send you a link to reset your password.</p>

          {error && (
            <div style={{ background: "var(--danger-50)", border: "1px solid var(--danger-200)", borderRadius: 8, padding: "10px 14px", marginBottom: 16, display: "flex", gap: 10, alignItems: "flex-start" }}>
              <Icon name="alert-circle" size={16} style={{ color: "var(--danger-600)", flexShrink: 0, marginTop: 1 }} />
              <span style={{ fontSize: 13.5, color: "var(--danger-700)" }}>{error}</span>
            </div>
          )}

          <div>
            <label className="field-label">Email address</label>
            <input className="input" type="email" required placeholder="you@company.com" value={email} onChange={e => { setEmail(e.target.value); clearError(); }} />
          </div>

          <div ref={turnstileRef} style={{ marginTop: 14 }} />

          <button type="submit" className="btn btn-gold btn-block btn-lg" style={{ marginTop: 20, opacity: loading ? .7 : 1 }} disabled={loading}>
            {loading
              ? <><Icon name="loader-circle" size={16} style={{ animation: "spin 1s linear infinite" }} /> Sending…</>
              : "Send reset link"}
          </button>

          <p className="muted" style={{ textAlign: "center", fontSize: 13.5, marginTop: 16 }}>
            <a onClick={() => { setMode("login"); clearError(); }} style={{ cursor: "pointer", color: "var(--navy-700)", fontWeight: 600 }}>
              Back to log in
            </a>
          </p>
        </form>
      </div>
    );
  }

  // ── Set new password form (after clicking reset link) ────────

  if (mode === "reset") {
    return (
      <div className="route-anim" style={{ display: "flex", alignItems: "center", justifyContent: "center", minHeight: "calc(100vh - var(--nav-h))", padding: 24, background: "var(--paper)" }}>
        <form onSubmit={handleResetPassword} style={{ width: "min(420px, 100%)" }}>
          <h1 style={{ fontSize: 24, marginBottom: 6 }}>Set a new password</h1>
          <p className="muted" style={{ fontSize: 14, marginBottom: 20 }}>Choose a new password for your account.</p>

          {error && (
            <div style={{ background: "var(--danger-50)", border: "1px solid var(--danger-200)", borderRadius: 8, padding: "10px 14px", marginBottom: 16, display: "flex", gap: 10, alignItems: "flex-start" }}>
              <Icon name="alert-circle" size={16} style={{ color: "var(--danger-600)", flexShrink: 0, marginTop: 1 }} />
              <span style={{ fontSize: 13.5, color: "var(--danger-700)" }}>{error}</span>
            </div>
          )}

          <div>
            <label className="field-label">New password</label>
            <input className="input" type="password" required placeholder="••••••••" minLength={8} value={password} onChange={e => { setPassword(e.target.value); clearError(); }} />
          </div>

          <button type="submit" className="btn btn-gold btn-block btn-lg" style={{ marginTop: 20, opacity: loading ? .7 : 1 }} disabled={loading}>
            {loading
              ? <><Icon name="loader-circle" size={16} style={{ animation: "spin 1s linear infinite" }} /> Updating…</>
              : "Update password"}
          </button>
        </form>
      </div>
    );
  }

  // ── Main form ─────────────────────────────────────────────────

  const submit = mode === "login" ? handleLogin : handleRegister;

  return (
    <div className="route-anim auth-layout" style={{ display: "grid", gridTemplateColumns: "1fr 1fr", minHeight: "calc(100vh - var(--nav-h))" }}>

      {/* Left brand panel */}
      <div className="auth-aside" style={{ background: "linear-gradient(160deg, var(--navy-800), var(--navy-600))", color: "#fff", padding: "56px 56px", display: "flex", flexDirection: "column", justifyContent: "center", position: "relative", overflow: "hidden" }}>
        <div style={{ position: "absolute", inset: 0, opacity: .4, backgroundImage: "linear-gradient(rgba(255,255,255,.05) 1px, transparent 1px), linear-gradient(90deg, rgba(255,255,255,.05) 1px, transparent 1px)", backgroundSize: "40px 40px" }} />
        <div style={{ position: "relative", maxWidth: 420 }}>
          <h2 style={{ fontSize: 34, color: "#fff", lineHeight: 1.18, maxWidth: 380 }}>
            {role === "supplier" ? "Grow your business across Africa" : "Source smarter, trade with confidence"}
          </h2>
          <p style={{ color: "var(--navy-200)", fontSize: 16, marginTop: 20, lineHeight: 1.6 }}>
            {role === "supplier"
              ? "List products free, get a branded store page, and reach 118,000+ verified buyers across 54 countries."
              : "Compare verified suppliers, send inquiries, and post RFQs — all in one place."}
          </p>
          <div style={{ display: "flex", flexDirection: "column", gap: 14, marginTop: 32 }}>
            {[["badge-check", "Verified suppliers & trade assurance"], ["globe", "All 54 African countries"], ["zap", "Fast quotes — most reply within hours"]].map(([ic, t]) => (
              <div key={t} style={{ display: "flex", alignItems: "center", gap: 12 }}>
                <span style={{ width: 38, height: 38, borderRadius: 10, background: "rgba(232,184,75,.18)", color: "var(--gold-400)", display: "flex", alignItems: "center", justifyContent: "center", flexShrink: 0 }}><Icon name={ic} size={18} /></span>
                <span style={{ color: "var(--navy-100)", fontSize: 15 }}>{t}</span>
              </div>
            ))}
          </div>
        </div>
      </div>

      {/* Right form */}
      <div style={{ display: "flex", alignItems: "center", justifyContent: "center", padding: "20px 24px", background: "var(--paper)" }}>
        <form onSubmit={submit} style={{ width: "min(420px, 100%)" }}>

          {/* Mode toggle */}
          <div style={{ display: "flex", background: "var(--paper-2)", borderRadius: 10, padding: 4, marginBottom: 12 }}>
            {["login", "register"].map(m => (
              <button key={m} type="button" onClick={() => { setMode(m); clearError(); }}
                style={{ flex: 1, padding: "7px 0", borderRadius: 7, fontWeight: 600, fontSize: 13.5, background: mode === m ? "#fff" : "transparent", color: mode === m ? "var(--navy-800)" : "var(--ink-500)", boxShadow: mode === m ? "var(--sh-sm)" : "none" }}>
                {m === "login" ? "Log in" : "Register"}
              </button>
            ))}
          </div>

          <h1 style={{ fontSize: 20, marginBottom: 3 }}>{mode === "login" ? "Welcome back" : "Create your account"}</h1>
          <p className="muted" style={{ fontSize: 13, marginBottom: 12 }}>{mode === "login" ? "Log in to your AfricaMart account" : "Join the pan-African B2B marketplace"}</p>

          {/* Error banner */}
          {error && (
            <div style={{ background: "var(--danger-50)", border: "1px solid var(--danger-200)", borderRadius: 8, padding: "8px 12px", marginBottom: 10, display: "flex", gap: 10, alignItems: "flex-start" }}>
              <Icon name="alert-circle" size={16} style={{ color: "var(--danger-600)", flexShrink: 0, marginTop: 1 }} />
              <span style={{ fontSize: 13, color: "var(--danger-700)" }}>{error}</span>
            </div>
          )}

          {/* Google OAuth */}
          <button type="button" className="btn btn-ghost btn-block" onClick={handleGoogle} disabled={loading}
            style={{ padding: "9px", marginBottom: 10, opacity: loading ? .6 : 1 }}>
            <svg width="16" height="16" viewBox="0 0 48 48"><path fill="#EA4335" d="M24 9.5c3.5 0 6.6 1.2 9 3.6l6.7-6.7C35.6 2.4 30.1 0 24 0 14.6 0 6.5 5.4 2.6 13.2l7.8 6.1C12.2 13.4 17.6 9.5 24 9.5z"/><path fill="#4285F4" d="M46.5 24.5c0-1.6-.1-3.1-.4-4.5H24v9h12.7c-.5 3-2.2 5.5-4.7 7.2l7.3 5.7C43.8 37.9 46.5 31.8 46.5 24.5z"/><path fill="#FBBC05" d="M10.4 28.3c-.5-1.5-.8-3.1-.8-4.8s.3-3.3.8-4.8l-7.8-6.1C1 16 0 19.9 0 24s1 8 2.6 11.4l7.8-6.1z"/><path fill="#34A853" d="M24 48c6.1 0 11.3-2 15-5.5l-7.3-5.7c-2 1.4-4.7 2.3-7.7 2.3-6.4 0-11.8-3.9-13.6-9.8l-7.8 6.1C6.5 42.6 14.6 48 24 48z"/></svg>
            Continue with Google
          </button>

          <div style={{ display: "flex", alignItems: "center", gap: 12, margin: "10px 0", color: "var(--ink-400)", fontSize: 11.5 }}>
            <span style={{ flex: 1, height: 1, background: "var(--border)" }} />
            or {mode === "login" ? "log in" : "sign up"} with email
            <span style={{ flex: 1, height: 1, background: "var(--border)" }} />
          </div>

          {mode === "register" && !roleLocked && (
            <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 10, marginBottom: 10 }}>
              {[["buyer", "shopping-cart", "I'm a buyer"], ["supplier", "store", "I'm a supplier"]].map(([r, ic, t]) => (
                <button key={r} type="button" onClick={() => setRole(r)}
                  style={{ padding: "9px 10px", borderRadius: 10, display: "flex", alignItems: "center", gap: 8, textAlign: "left", border: "2px solid " + (role === r ? "var(--gold-500)" : "var(--border)"), background: role === r ? "var(--gold-50)" : "#fff" }}>
                  <Icon name={ic} size={16} style={{ color: role === r ? "var(--gold-700)" : "var(--ink-500)", flexShrink: 0 }} />
                  <span style={{ fontWeight: 700, fontSize: 13.5 }}>{t}</span>
                </button>
              ))}
            </div>
          )}

          {mode === "register" && roleLocked && (
            <div style={{ display: "flex", alignItems: "center", gap: 8, padding: "9px 10px", borderRadius: 10, border: "2px solid var(--gold-500)", background: "var(--gold-50)", marginBottom: 10 }}>
              <Icon name={role === "supplier" ? "store" : "shopping-cart"} size={16} style={{ color: "var(--gold-700)", flexShrink: 0 }} />
              <span style={{ fontWeight: 700, fontSize: 13.5 }}>{role === "supplier" ? "Creating a supplier account" : "Creating a buyer account"}</span>
            </div>
          )}

          <div style={{ display: "flex", flexDirection: "column", gap: 9 }}>
            {mode === "register" && (
              <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 12 }}>
                <div>
                  <label className="field-label">Full name</label>
                  <input className="input" required placeholder="Amina Okoye" value={name} onChange={e => setName(e.target.value)} />
                </div>
                <div>
                  <label className="field-label">{role === "supplier" ? "Company name" : "Company"}</label>
                  <input className="input" required placeholder="Acme Trading Ltd" value={company} onChange={e => setCompany(e.target.value)} />
                </div>
              </div>
            )}

            <div>
              <label className="field-label">Email address</label>
              <input className="input" type="email" required placeholder="you@company.com" value={email} onChange={e => { setEmail(e.target.value); clearError(); }} />
            </div>

            {mode === "register" && (
              <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 12 }}>
                <div>
                  <label className="field-label">Country</label>
                  <select className="select" required value={country} onChange={e => setCountry(e.target.value)}>
                    <option value="" disabled>Select…</option>
                    {AM.COUNTRIES.map(c => <option key={c.code} value={c.code}>{c.name}</option>)}
                  </select>
                </div>
                <div>
                  <label className="field-label">Phone</label>
                  <input className="input" required placeholder="+254 …" value={phone} onChange={e => setPhone(e.target.value)} />
                </div>
              </div>
            )}

            {mode === "register" && role === "buyer" && (
              <div>
                <label className="field-label">Industry</label>
                <select className="select" defaultValue="">
                  <option value="" disabled>Select…</option>
                  {AM.CATEGORIES.map(c => <option key={c.id}>{c.name}</option>)}
                </select>
              </div>
            )}

            <div>
              <div style={{ display: "flex", justifyContent: "space-between", alignItems: "baseline" }}>
                <label className="field-label">Password</label>
                {mode === "login" && (
                  <a onClick={() => { setMode("forgot"); clearError(); }} style={{ cursor: "pointer", fontSize: 12.5, color: "var(--navy-700)", fontWeight: 600 }}>
                    Forgot password?
                  </a>
                )}
              </div>
              <input className="input" type="password" required placeholder="••••••••" minLength={mode === "register" ? 8 : undefined} value={password} onChange={e => { setPassword(e.target.value); clearError(); }} />
            </div>
          </div>

          {mode === "register" && (
            <p className="muted" style={{ fontSize: 12, marginTop: 8, display: "flex", gap: 6, alignItems: "flex-start", lineHeight: 1.45 }}>
              <Icon name={role === "supplier" ? "rocket" : "mail-check"} size={14} style={{ color: role === "supplier" ? "var(--gold-600)" : "var(--green-600)", flexShrink: 0, marginTop: 1 }} />
              {role === "supplier"
                ? "We'll email a verification link — then add products, certifications and trade details from your dashboard."
                : "We'll send a verification link to confirm your email before activating your account."}
            </p>
          )}

          <div ref={turnstileRef} style={{ marginTop: 14 }} />

          <button type="submit" className="btn btn-gold btn-block btn-lg" style={{ marginTop: 12, opacity: loading ? .7 : 1 }} disabled={loading}>
            {loading
              ? <><Icon name="loader-circle" size={16} style={{ animation: "spin 1s linear infinite" }} /> {mode === "login" ? "Logging in…" : "Creating account…"}</>
              : (mode === "login" ? "Log in" : "Create account")}
          </button>

          <p className="muted" style={{ textAlign: "center", fontSize: 12.5, marginTop: 10 }}>
            {mode === "login" ? "New to AfricaMart? " : "Already have an account? "}
            <a onClick={() => { setMode(mode === "login" ? "register" : "login"); clearError(); }}
              style={{ cursor: "pointer", color: "var(--navy-700)", fontWeight: 600 }}>
              {mode === "login" ? "Create an account" : "Log in"}
            </a>
          </p>
        </form>
      </div>
    </div>
  );
}

Object.assign(window, { AuthPage });
