/* ============================================================
   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 [selProducts, setSelProducts] = useState([]);

  // 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

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

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

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

  async function afterSignIn(user, extraMeta = {}) {
    const auth = DB.buildAuthState(user);
    // Ensure buyer or supplier row exists
    try {
      if (auth.role === "supplier") {
        await DB.ensureSupplierRecord(user, extraMeta);
      } else {
        await DB.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");
    setLoading(true); setError("");
    try {
      const { user } = await DB.auth.signIn(email, password);
      await afterSignIn(user);
    } catch (err) {
      setError(friendlyError(err.message));
    } finally {
      setLoading(false);
    }
  }

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

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

      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));
    } 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("rate limit"))                 return "Too many attempts. Please wait a moment.";
    return msg;
  }

  const prodOptions = ["Steel & Metal", "Agriculture", "Construction", "Textiles", "Chemicals", "Machinery", "Food & Beverage", "Plastics"];

  // ── 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>
    );
  }

  // ── 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: "40px 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: 24 }}>
            {["login", "register"].map(m => (
              <button key={m} type="button" onClick={() => { setMode(m); clearError(); }}
                style={{ flex: 1, padding: "9px 0", borderRadius: 7, fontWeight: 600, fontSize: 14.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: 24, marginBottom: 6 }}>{mode === "login" ? "Welcome back" : "Create your account"}</h1>
          <p className="muted" style={{ fontSize: 14, marginBottom: 20 }}>{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: "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>
          )}

          {/* Google OAuth */}
          <button type="button" className="btn btn-ghost btn-block" onClick={handleGoogle} disabled={loading}
            style={{ padding: "12px", marginBottom: 16, opacity: loading ? .6 : 1 }}>
            <svg width="18" height="18" 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: "16px 0", color: "var(--ink-400)", fontSize: 12.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" && (
            <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 10, marginBottom: 18 }}>
              {[["buyer", "shopping-cart", "I'm a buyer", "Source products"], ["supplier", "store", "I'm a supplier", "Sell products"]].map(([r, ic, t, d]) => (
                <button key={r} type="button" onClick={() => setRole(r)}
                  style={{ padding: 14, borderRadius: 12, textAlign: "left", border: "2px solid " + (role === r ? "var(--gold-500)" : "var(--border)"), background: role === r ? "var(--gold-50)" : "#fff" }}>
                  <Icon name={ic} size={20} style={{ color: role === r ? "var(--gold-700)" : "var(--ink-500)" }} />
                  <div style={{ fontWeight: 700, fontSize: 14, marginTop: 8 }}>{t}</div>
                  <div className="muted" style={{ fontSize: 12 }}>{d}</div>
                </button>
              ))}
            </div>
          )}

          <div style={{ display: "flex", flexDirection: "column", gap: 14 }}>
            {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>
            )}

            {mode === "register" && role === "supplier" && (
              <>
                <div>
                  <label className="field-label">Business type</label>
                  <select className="select" required defaultValue="">
                    <option value="" disabled>Select…</option>
                    {["Manufacturer", "Exporter", "Distributor", "Wholesaler", "Trading company"].map(t => <option key={t}>{t}</option>)}
                  </select>
                </div>
                <div>
                  <label className="field-label">Products / services</label>
                  <div style={{ display: "flex", gap: 6, flexWrap: "wrap" }}>
                    {prodOptions.map(p => {
                      const on = selProducts.includes(p);
                      return (
                        <button key={p} type="button" onClick={() => setSelProducts(on ? selProducts.filter(x => x !== p) : [...selProducts, p])}
                          className="badge" style={{ cursor: "pointer", border: "1px solid " + (on ? "var(--gold-500)" : "var(--border-strong)"), background: on ? "var(--gold-100)" : "#fff", color: on ? "var(--gold-700)" : "var(--ink-600)", padding: "6px 12px", fontSize: 13 }}>
                          {on && <Icon name="check" size={12} />} {p}
                        </button>
                      );
                    })}
                  </div>
                </div>
                <div>
                  <label className="field-label">GST / Trade license</label>
                  <div style={{ border: "1.5px dashed var(--border-strong)", borderRadius: 10, padding: "18px", textAlign: "center", cursor: "pointer", background: "#fff" }}>
                    <Icon name="upload-cloud" size={24} style={{ color: "var(--ink-400)" }} />
                    <div style={{ fontSize: 13.5, fontWeight: 600, marginTop: 6 }}>Upload license document</div>
                    <div className="muted" style={{ fontSize: 12 }}>PDF, JPG or PNG · max 5MB</div>
                  </div>
                </div>
              </>
            )}

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

          {mode === "register" && (
            <p className="muted" style={{ fontSize: 12.5, marginTop: 12, display: "flex", gap: 7, alignItems: "flex-start" }}>
              <Icon name="mail-check" size={15} style={{ color: "var(--green-600)", flexShrink: 0, marginTop: 1 }} />
              We'll send a verification link to confirm your email before activating your account.
            </p>
          )}

          <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" }} /> {mode === "login" ? "Logging in…" : "Creating account…"}</>
              : (mode === "login" ? "Log in" : "Create account")}
          </button>

          <p className="muted" style={{ textAlign: "center", fontSize: 13.5, marginTop: 16 }}>
            {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 });
