// screens-auth.jsx — phone OTP sign-in + profile onboarding
const { useState: useAuth, useRef: useAuthRef } = React;

/* ── AuthGate (email OTP + Google) ─────────────────────────── */
function AuthGate({ onAuth, demoMode, backUrl, backLabel = "Back to app" }) {
  const [mode, setMode] = useAuth("signin");   // "signin" | "signup" | "forgot" | "verify_signup"
  const [email, setEmail] = useAuth("");
  const [password, setPassword] = useAuth("");
  const [phone, setPhone] = useAuth("");
  const [code, setCode] = useAuth("");
  const [showPassword, setShowPassword] = useAuth(false);
  const [loading, setLoading] = useAuth(false);
  const [error, setError] = useAuth("");
  const [message, setMessage] = useAuth("");

  if (demoMode) return null;

  const validEmail = (e) => /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(e);

  const handleSignIn = async () => {
    const e = email.trim().toLowerCase();
    if (!validEmail(e)) { setError("Enter a valid email address."); return; }
    if (!password) { setError("Enter your password."); return; }
    setLoading(true); setError(""); setMessage("");
    const { session, user, error: err } = await Auth.signInPassword(e, password);
    setLoading(false);
    if (err) { setError(prettyAuthError(err)); return; }
  };

  const handleSignUp = async () => {
    const e = email.trim().toLowerCase();
    if (!validEmail(e)) { setError("Enter a valid email address."); return; }
    if (password.length < 6) { setError("Password must be at least 6 characters."); return; }
    setLoading(true); setError(""); setMessage("");
    const { session, user, error: err } = await Auth.signUpPassword(e, password);
    setLoading(false);
    if (err) { setError(prettyAuthError(err)); return; }
    
    // If Supabase logs the user in immediately (email confirmation disabled)
    if (session) {
      return;
    }
    
    // Go to OTP verification step
    setMode("verify_signup");
    setMessage("Verification code sent! Please check your email inbox.");
  };

  const handleVerifySignUp = async () => {
    const c = code.replace(/\s/g, "");
    if (c.length < 6) { setError("Enter the full 6-digit code."); return; }
    setLoading(true); setError(""); setMessage("");
    const { session, user, error: err } = await Auth.verifySignupOTP(email, c);
    setLoading(false);
    if (err) { setError(prettyAuthError(err)); return; }
  };

  const handleSendPhoneOTP = async () => {
    const p = phone.trim();
    if (!p) { setError("Enter your mobile number."); return; }
    // basic validation, ensuring +91 if needed, or assume they enter it
    const formattedPhone = p.startsWith("+") ? p : `+91${p}`;
    setLoading(true); setError(""); setMessage("");
    const { error: err } = await Auth.sendPhoneOTP(formattedPhone);
    setLoading(false);
    if (err) { setError(prettyAuthError(err)); return; }
    setMode("verify_phone_otp");
    setMessage("Verification code sent to your phone!");
  };

  const handleVerifyPhoneOTP = async () => {
    const c = code.replace(/\s/g, "");
    if (c.length < 6) { setError("Enter the full 6-digit code."); return; }
    const p = phone.trim();
    const formattedPhone = p.startsWith("+") ? p : `+91${p}`;
    setLoading(true); setError(""); setMessage("");
    const { session, user, error: err } = await Auth.verifyPhoneOTP(formattedPhone, c);
    setLoading(false);
    if (err) { setError(prettyAuthError(err)); return; }
  };

  const handleResendOTP = async () => {
    setLoading(true); setError(""); setMessage("");
    const { error: err } = await Auth.signUpPassword(email, password);
    setLoading(false);
    if (err) { setError(prettyAuthError(err)); return; }
    setMessage("Verification code resent! Please check your inbox.");
  };

  const handleForgot = async () => {
    const e = email.trim().toLowerCase();
    if (!validEmail(e)) { setError("Enter a valid email address."); return; }
    setLoading(true); setError(""); setMessage("");
    const { error: err } = await Auth.resetPassword(e);
    setLoading(false);
    if (err) { setError(prettyAuthError(err)); return; }
    setMessage("Password reset email sent! Please check your inbox.");
  };

  return (
    <div style={{ minHeight: "100vh", display: "flex", alignItems: "center", justifyContent: "center", background: "var(--paper)", padding: 24 }}>
      <div style={{ width: "100%", maxWidth: 420 }}>
        {backUrl && (
          <div style={{ marginBottom: 12 }}>
            <button onClick={() => { window.location.href = backUrl; }} style={{ display: "inline-flex", alignItems: "center", gap: 6, background: "none", border: "none", cursor: "pointer", color: "var(--ink-2)", fontFamily: "var(--sans)", fontSize: 14.5, fontWeight: 600, padding: "8px 0" }}>
              <Icon name="back" size={15} /> {backLabel}
            </button>
          </div>
        )}

        {/* logo */}
        <div style={{ textAlign: "center", marginBottom: 40 }}>
          <span style={{ display: "inline-flex", alignItems: "center", gap: 10 }}>
            <span style={{ width: 40, height: 40, borderRadius: 12, background: "var(--clay)", display: "grid", placeItems: "center" }}>
              <Icon name="users" size={22} stroke={2} style={{ color: "#fff" }} />
            </span>
            <span style={{ fontFamily: "var(--display)", fontWeight: 700, fontSize: 26, letterSpacing: "-0.03em", color: "var(--ink)" }}>TaskPe</span>
          </span>
        </div>

        <div style={{ background: "var(--surface)", border: "1px solid var(--line)", borderRadius: 24, padding: 32 }}>

          {mode === "signin" && (
            <>
              <h2 style={{ fontFamily: "var(--display)", fontWeight: 600, fontSize: 28, letterSpacing: "-0.03em", margin: "0 0 6px", color: "var(--ink)" }}>Sign in</h2>
              <p style={{ margin: "0 0 26px", fontSize: 15.5, color: "var(--ink-2)", lineHeight: 1.5 }}>Welcome back! Sign in to your account.</p>

              <label style={{ display: "block", marginBottom: 16 }}>
                <div style={{ fontSize: 13.5, fontWeight: 700, color: "var(--ink)", marginBottom: 8 }}>Email address</div>
                <input
                  type="email" value={email} autoFocus
                  onChange={e => { setEmail(e.target.value); setError(""); setMessage(""); }}
                  placeholder="you@example.com" autoComplete="email"
                  style={authInputStyle}
                />
              </label>

              <label style={{ display: "block", marginBottom: 8 }}>
                <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center", marginBottom: 8 }}>
                  <div style={{ fontSize: 13.5, fontWeight: 700, color: "var(--ink)" }}>Password</div>
                  <button onClick={() => setMode("forgot")} style={{ background: "none", border: "none", cursor: "pointer", color: "var(--clay)", fontSize: 13, fontWeight: 600, padding: 0 }}>Forgot password?</button>
                </div>
                <div style={{ position: "relative", display: "flex", alignItems: "center" }}>
                  <input
                    type={showPassword ? "text" : "password"} value={password}
                    onChange={e => { setPassword(e.target.value); setError(""); setMessage(""); }}
                    onKeyDown={e => e.key === "Enter" && handleSignIn()}
                    placeholder="Enter password" autoComplete="current-password"
                    style={{ ...authInputStyle, paddingRight: 64 }}
                  />
                  <button onClick={() => setShowPassword(s => !s)} type="button" style={{ position: "absolute", right: 12, background: "none", border: "none", cursor: "pointer", color: "var(--ink-2)", fontFamily: "var(--sans)", fontSize: 13, fontWeight: 600 }}>
                    {showPassword ? "Hide" : "Show"}
                  </button>
                </div>
              </label>

              {error && <ErrMsg text={error} />}
              {message && <div style={{ color: "var(--green)", fontSize: 14.5, fontWeight: 600, marginBottom: 16 }}>{message}</div>}

              <Button full size="lg" onClick={handleSignIn} disabled={loading} style={{ marginTop: 16 }}>
                {loading ? "Signing in…" : "Sign in"}
              </Button>

              <div style={{ textAlign: "center", margin: "16px 0", color: "var(--ink-2)", fontSize: 13, fontWeight: 600 }}>OR</div>

              <Button full variant="outline" size="lg" onClick={() => { setMode("phone_signin"); setError(""); setMessage(""); }} disabled={loading}>
                Continue with Phone Number
              </Button>

              <p style={{ marginTop: 20, fontSize: 14.5, color: "var(--ink-2)", textAlign: "center" }}>
                Don't have an account?{" "}
                <button onClick={() => { setMode("signup"); setError(""); setMessage(""); }} style={linkBtn}>Sign up</button>
              </p>
            </>
          )}

          {mode === "phone_signin" && (
            <>
              <button onClick={() => { setMode("signin"); setError(""); setMessage(""); }} style={{ display: "inline-flex", alignItems: "center", gap: 6, background: "none", border: "none", cursor: "pointer", color: "var(--ink-2)", fontFamily: "var(--sans)", fontSize: 14.5, fontWeight: 600, padding: "0 0 20px" }}>
                <Icon name="back" size={15} /> Back
              </button>
              <h2 style={{ fontFamily: "var(--display)", fontWeight: 600, fontSize: 28, letterSpacing: "-0.03em", margin: "0 0 6px", color: "var(--ink)" }}>Sign in with Phone</h2>
              <p style={{ margin: "0 0 26px", fontSize: 15.5, color: "var(--ink-2)", lineHeight: 1.5 }}>We'll send you an OTP to log in securely.</p>

              <label style={{ display: "block", marginBottom: 16 }}>
                <div style={{ fontSize: 13.5, fontWeight: 700, color: "var(--ink)", marginBottom: 8 }}>Mobile Number</div>
                <input
                  type="tel" value={phone} autoFocus
                  onChange={e => { 
                    const val = e.target.value;
                    if (/[^\d+]/.test(val)) setError("Phone number can only contain numbers.");
                    else setError("");
                    setPhone(val.replace(/[^\d+]/g, "")); 
                    setMessage(""); 
                  }}
                  onKeyDown={e => e.key === "Enter" && handleSendPhoneOTP()}
                  placeholder="e.g. 9876543210" autoComplete="tel"
                  style={authInputStyle}
                />
                <div style={{ fontSize: 12.5, color: "var(--ink-2)", marginTop: 6 }}>Enter your 10-digit number.</div>
              </label>

              {error && <ErrMsg text={error} />}
              {message && <div style={{ color: "var(--green)", fontSize: 14.5, fontWeight: 600, marginBottom: 16 }}>{message}</div>}

              <Button full size="lg" onClick={handleSendPhoneOTP} disabled={loading || phone.length < 10} style={{ marginTop: 16 }}>
                {loading ? "Sending OTP…" : "Get OTP"}
              </Button>
            </>
          )}

          {mode === "verify_phone_otp" && (
            <>
              <button onClick={() => { setMode("phone_signin"); setCode(""); setError(""); setMessage(""); }} style={{ display: "inline-flex", alignItems: "center", gap: 6, background: "none", border: "none", cursor: "pointer", color: "var(--ink-2)", fontFamily: "var(--sans)", fontSize: 14.5, fontWeight: 600, padding: "0 0 20px" }}>
                <Icon name="back" size={15} /> Back
              </button>

              <div style={{ width: 52, height: 52, borderRadius: "50%", background: "var(--green-3)", color: "var(--green)", display: "grid", placeItems: "center", marginBottom: 18 }}>
                <Icon name="chat" size={26} stroke={1.8} />
              </div>

              <h2 style={{ fontFamily: "var(--display)", fontWeight: 600, fontSize: 26, letterSpacing: "-0.03em", margin: "0 0 8px", color: "var(--ink)" }}>Enter OTP</h2>
              <p style={{ margin: "0 0 26px", fontSize: 15, color: "var(--ink-2)", lineHeight: 1.55 }}>
                We sent a verification code to <strong style={{ color: "var(--ink)" }}>{phone}</strong>.
              </p>

              <label style={{ display: "block", marginBottom: 16 }}>
                <div style={{ fontSize: 13.5, fontWeight: 700, color: "var(--ink)", marginBottom: 8 }}>Verification code</div>
                <input
                  type="text" inputMode="numeric" pattern="[0-9]*" maxLength={6}
                  value={code} autoFocus
                  onChange={e => { setCode(e.target.value.replace(/\D/g, "")); setError(""); }}
                  onKeyDown={e => e.key === "Enter" && handleVerifyPhoneOTP()}
                  placeholder="Enter code" autoComplete="one-time-code"
                  style={{ ...authInputStyle, fontSize: 26, letterSpacing: "0.2em", textAlign: "center", fontWeight: 700 }}
                />
              </label>

              {error && <ErrMsg text={error} />}
              {message && <div style={{ color: "var(--green)", fontSize: 14.5, fontWeight: 600, marginBottom: 16 }}>{message}</div>}

              <Button full size="lg" icon="check" onClick={handleVerifyPhoneOTP} disabled={loading || code.length < 6} style={{ marginTop: 4 }}>
                {loading ? "Verifying…" : "Verify & Sign In"}
              </Button>
            </>
          )}

          {mode === "signup" && (
            <>
              <h2 style={{ fontFamily: "var(--display)", fontWeight: 600, fontSize: 28, letterSpacing: "-0.03em", margin: "0 0 6px", color: "var(--ink)" }}>Create account</h2>
              <p style={{ margin: "0 0 26px", fontSize: 15.5, color: "var(--ink-2)", lineHeight: 1.5 }}>Sign up to start posting or taking tasks.</p>

              <label style={{ display: "block", marginBottom: 16 }}>
                <div style={{ fontSize: 13.5, fontWeight: 700, color: "var(--ink)", marginBottom: 8 }}>Email address</div>
                <input
                  type="email" value={email} autoFocus
                  onChange={e => { setEmail(e.target.value); setError(""); setMessage(""); }}
                  placeholder="you@example.com" autoComplete="email"
                  style={authInputStyle}
                />
              </label>

              <label style={{ display: "block", marginBottom: 16 }}>
                <div style={{ fontSize: 13.5, fontWeight: 700, color: "var(--ink)", marginBottom: 8 }}>Password</div>
                <div style={{ position: "relative", display: "flex", alignItems: "center" }}>
                  <input
                    type={showPassword ? "text" : "password"} value={password}
                    onChange={e => { setPassword(e.target.value); setError(""); setMessage(""); }}
                    onKeyDown={e => e.key === "Enter" && handleSignUp()}
                    placeholder="At least 6 characters" autoComplete="new-password"
                    style={{ ...authInputStyle, paddingRight: 64 }}
                  />
                  <button onClick={() => setShowPassword(s => !s)} type="button" style={{ position: "absolute", right: 12, background: "none", border: "none", cursor: "pointer", color: "var(--ink-2)", fontFamily: "var(--sans)", fontSize: 13, fontWeight: 600 }}>
                    {showPassword ? "Hide" : "Show"}
                  </button>
                </div>
              </label>

              {error && <ErrMsg text={error} />}
              {message && <div style={{ color: "var(--green)", fontSize: 14.5, fontWeight: 600, marginBottom: 16 }}>{message}</div>}

              <Button full size="lg" onClick={handleSignUp} disabled={loading} style={{ marginTop: 16 }}>
                {loading ? "Creating account…" : "Sign up"}
              </Button>

              <div style={{ textAlign: "center", margin: "16px 0", color: "var(--ink-2)", fontSize: 13, fontWeight: 600 }}>OR</div>

              <Button full variant="outline" size="lg" onClick={() => { setMode("phone_signin"); setError(""); setMessage(""); }} disabled={loading}>
                Continue with Phone Number
              </Button>

              <p style={{ marginTop: 20, fontSize: 14.5, color: "var(--ink-2)", textAlign: "center" }}>
                Already have an account?{" "}
                <button onClick={() => { setMode("signin"); setError(""); setMessage(""); }} style={linkBtn}>Sign in</button>
              </p>
            </>
          )}

          {mode === "verify_signup" && (
            <>
              <button onClick={() => { setMode("signup"); setCode(""); setError(""); setMessage(""); }} style={{ display: "inline-flex", alignItems: "center", gap: 6, background: "none", border: "none", cursor: "pointer", color: "var(--ink-2)", fontFamily: "var(--sans)", fontSize: 14.5, fontWeight: 600, padding: "0 0 20px" }}>
                <Icon name="back" size={15} /> Back
              </button>

              <div style={{ width: 52, height: 52, borderRadius: "50%", background: "var(--green-3)", color: "var(--green)", display: "grid", placeItems: "center", marginBottom: 18 }}>
                <Icon name="chat" size={26} stroke={1.8} />
              </div>

              <h2 style={{ fontFamily: "var(--display)", fontWeight: 600, fontSize: 26, letterSpacing: "-0.03em", margin: "0 0 8px", color: "var(--ink)" }}>Confirm your email</h2>
              <p style={{ margin: "0 0 26px", fontSize: 15, color: "var(--ink-2)", lineHeight: 1.55 }}>
                We sent a verification code to <strong style={{ color: "var(--ink)" }}>{email}</strong>.
              </p>

              <label style={{ display: "block", marginBottom: 16 }}>
                <div style={{ fontSize: 13.5, fontWeight: 700, color: "var(--ink)", marginBottom: 8 }}>Verification code</div>
                <input
                  type="text" inputMode="numeric" pattern="[0-9]*" maxLength={10}
                  value={code} autoFocus
                  onChange={e => { setCode(e.target.value.replace(/\D/g, "")); setError(""); }}
                  onKeyDown={e => e.key === "Enter" && handleVerifySignUp()}
                  placeholder="Enter code" autoComplete="one-time-code"
                  style={{ ...authInputStyle, fontSize: 26, letterSpacing: "0.2em", textAlign: "center", fontWeight: 700 }}
                />
              </label>

              {error && <ErrMsg text={error} />}
              {message && <div style={{ color: "var(--green)", fontSize: 14.5, fontWeight: 600, marginBottom: 16 }}>{message}</div>}

              <Button full size="lg" icon="check" onClick={handleVerifySignUp} disabled={loading || code.length < 6} style={{ marginTop: 4 }}>
                {loading ? "Verifying…" : "Verify & Sign Up"}
              </Button>

              <p style={{ marginTop: 20, fontSize: 14.5, color: "var(--ink-2)", textAlign: "center" }}>
                Didn't get the code?{" "}
                <button onClick={handleResendOTP} disabled={loading} style={linkBtn}>Resend code</button>
              </p>
            </>
          )}

          {mode === "forgot" && (
            <>
              <button onClick={() => { setMode("signin"); setError(""); setMessage(""); }} style={{ display: "inline-flex", alignItems: "center", gap: 6, background: "none", border: "none", cursor: "pointer", color: "var(--ink-2)", fontFamily: "var(--sans)", fontSize: 14.5, fontWeight: 600, padding: "0 0 20px" }}>
                <Icon name="back" size={15} /> Back to Sign In
              </button>

              <h2 style={{ fontFamily: "var(--display)", fontWeight: 600, fontSize: 28, letterSpacing: "-0.03em", margin: "0 0 6px", color: "var(--ink)" }}>Reset password</h2>
              <p style={{ margin: "0 0 26px", fontSize: 15.5, color: "var(--ink-2)", lineHeight: 1.5 }}>Enter your email address and we'll send you a password reset link.</p>

              <label style={{ display: "block", marginBottom: 16 }}>
                <div style={{ fontSize: 13.5, fontWeight: 700, color: "var(--ink)", marginBottom: 8 }}>Email address</div>
                <input
                  type="email" value={email} autoFocus
                  onChange={e => { setEmail(e.target.value); setError(""); setMessage(""); }}
                  onKeyDown={e => e.key === "Enter" && handleForgot()}
                  placeholder="you@example.com" autoComplete="email"
                  style={authInputStyle}
                />
              </label>

              {error && <ErrMsg text={error} />}
              {message && <div style={{ color: "var(--green)", fontSize: 14.5, fontWeight: 600, marginBottom: 16 }}>{message}</div>}

              <Button full size="lg" onClick={handleForgot} disabled={loading} style={{ marginTop: 16 }}>
                {loading ? "Sending…" : "Send reset link"}
              </Button>
            </>
          )}
        </div>
      </div>
    </div>
  );
}

/* ── Onboarding survey (shown once after first sign-in) ────── */
const SKILL_SUGGEST = ["Photography", "Driving", "Writing", "Cooking", "Pet care", "Tech help", "Cleaning", "Heavy lifting", "Translation", "Social media"];
const AVAIL_DAYS = [["weekday", "Weekdays"], ["weekend", "Weekends"], ["morning", "Mornings"], ["afternoon", "Afternoons"], ["evening", "Evenings"]];
const AVAIL_HOURS = [["<10", "Under 10"], ["10-20", "10–20"], ["20-40", "20–40"], ["40+", "40+"]];
const TRAVEL_RADII = [["2", "Within 2 km"], ["5", "Within 5 km"], ["15", "Within 15 km"], ["city", "Anywhere in city"]];
const VEHICLES = [["none", "No vehicle 🚶"], ["bike", "Bike / scooter 🛵"], ["car", "Car 🚗"]];

function OnboardingGraphic({ step }) {
  const style = { width: 72, height: 72, marginBottom: 24, display: "block", color: "#ffffff", strokeWidth: 1.5 };
  if (step === "basics") {
    return (
      <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" style={style}>
        <rect x="5" y="2" width="14" height="20" rx="2" ry="2" />
        <line x1="12" y1="18" x2="12.01" y2="18" strokeWidth={3} />
        <circle cx="12" cy={9} r={3} />
        <path d="M6 20a6 6 0 0 1 12 0" />
      </svg>
    );
  }
  if (step === "role") {
    return (
      <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" style={style}>
        <path d="M17 21v-2a4 4 0 0 0-4-4H5a4 4 0 0 0-4 4v2" />
        <circle cx="9" cy={7} r="4" />
        <path d="M23 21v-2a4 4 0 0 0-3-3.87" />
        <path d="M16 3.13a4 4 0 0 1 0 7.75" />
      </svg>
    );
  }
  if (step === "categories") {
    return (
      <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" style={style}>
        <rect x="3" y="3" width="7" height="9" rx="1" />
        <rect x="14" y="3" width="7" height="5" rx="1" />
        <rect x="14" y="12" width="7" height="9" rx="1" />
        <rect x="3" y="16" width="7" height="5" rx="1" />
      </svg>
    );
  }
  if (step === "skills") {
    return (
      <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" style={style}>
        <polygon points="12 2 15.09 8.26 22 9.27 17 14.14 18.18 21.02 12 17.77 5.82 21.02 7 14.14 2 9.27 8.91 8.26 12 2" />
      </svg>
    );
  }
  if (step === "availability") {
    return (
      <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" style={style}>
        <rect x="3" y="4" width="18" height="18" rx="2" ry="2" />
        <line x1="16" y1="2" x2="16" y2="6" />
        <line x1="8" y1="2" x2="8" y2="6" />
        <line x1="3" y1="10" x2="21" y2="10" />
      </svg>
    );
  }
  if (step === "travel") {
    return (
      <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" style={style}>
        <path d="M21 10c0 7-9 13-9 13s-9-6-9-13a9 9 0 0 1 18 0z" />
        <circle cx="12" cy={10} r={3} />
      </svg>
    );
  }
  if (step === "bio") {
    return (
      <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" style={style}>
        <path d="M20 21v-2a4 4 0 0 0-4-4H8a4 4 0 0 0-4 4v2" />
        <circle cx="12" cy={7} r="4" />
      </svg>
    );
  }
  return null;
}

function OnboardingForm({ profile, onComplete }) {
  const [stepIdx, setStepIdx] = useAuth(0);
  const [role, setRole] = useAuth(null);
  const [cats, setCats] = useAuth(new Set());
  const [skills, setSkills] = useAuth([]);
  const [skillInput, setSkillInput] = useAuth("");
  const [availDays, setAvailDays] = useAuth(new Set());
  const [availHours, setAvailHours] = useAuth("");
  const [travel, setTravel] = useAuth("");
  const [vehicle, setVehicle] = useAuth("");
  const [bio, setBio] = useAuth("");
  const [photoFile, setPhotoFile] = useAuth(null);
  const [photoPreview, setPhotoPreview] = useAuth(null);
  const [name, setName] = useAuth(profile?.name && profile.name !== "You" ? profile.name : "");
  const [city, setCity] = useAuth("");
  const [phone, setPhone] = useAuth("");
  const [loading, setLoading] = useAuth(false);
  const [error, setError] = useAuth("");

  const ROLES = [
    { id: "worker", emoji: "💪", title: "I want to earn",      sub: "Find tasks nearby and get paid to help" },
    { id: "poster", emoji: "🧑‍💼", title: "I need things done", sub: "Post tasks and hire people in your city" },
    { id: "both",   emoji: "🤝", title: "Both",                sub: "I'll post tasks and take them too" },
  ];

  // role-aware step sequence — posters skip the worker-only steps
  const steps = role === "poster"
    ? ["role", "categories", "bio", "basics"]
    : ["role", "categories", "skills", "availability", "travel", "bio", "basics"];
  const total = steps.length;
  const key = steps[Math.min(stepIdx, total - 1)];

  const toggleIn = (setter) => (id) => setter(prev => { const n = new Set(prev); n.has(id) ? n.delete(id) : n.add(id); return n; });
  const toggleCat = toggleIn(setCats);
  const toggleDay = toggleIn(setAvailDays);

  const addSkill = (s) => {
    const v = (s ?? skillInput).trim();
    if (v && !skills.includes(v)) setSkills(prev => [...prev, v]);
    setSkillInput("");
  };
  const removeSkill = (s) => setSkills(prev => prev.filter(x => x !== s));
  const pickPhoto = (e) => { const f = e.target.files[0]; if (!f) return; setPhotoFile(f); setPhotoPreview(URL.createObjectURL(f)); };

  const submit = async () => {
    if (!name.trim()) { setError("Please enter your name."); return; }
    if (!city.trim()) { setError("Please enter your city."); return; }
    if (!phone.trim()) { setError("Please enter your phone number."); return; }
    if (phone.replace(/\D/g, "").length !== 10) { setError("Phone number must be exactly 10 digits."); return; }
    setLoading(true);
    await onComplete({
      role, name: name.trim(), city: city.trim(), phone: phone.trim(),
      preferredCategories: [...cats],
      skills, availabilityDays: [...availDays], availabilityHours: availHours,
      travelRadius: travel, vehicle, bio: bio.trim(),
      photoFile, photoPreview,
    });
  };

  const isLast = stepIdx === total - 1;
  const next = () => { setError(""); if (isLast) submit(); else setStepIdx(stepIdx + 1); };

  const canNext = () => {
    if (key === "role") return !!role;
    if (key === "basics") return !!name.trim() && !!city.trim() && !!phone.trim();
    return true;
  };
  const optionalEmpty =
    (key === "categories" && cats.size === 0) ||
    (key === "skills" && skills.length === 0) ||
    (key === "availability" && availDays.size === 0 && !availHours) ||
    (key === "travel" && !travel && !vehicle) ||
    (key === "bio" && !bio.trim() && !photoFile);
  const btnLabel = isLast ? (loading ? "Setting up your account…" : "Let's go")
    : key === "categories" && cats.size > 0 ? `Continue  ·  ${cats.size} selected`
    : optionalEmpty ? "Skip for now" : "Continue";

  const PANELS = {
    role:         { emoji: "👋", title: "Real people, real tasks.", body: "A marketplace where humans help humans — no bots, no algorithms deciding your worth." },
    categories:   { emoji: "🗂️", title: "Your city, your tasks.", body: "We match you with the right tasks in the categories you actually care about." },
    skills:       { emoji: "⭐", title: "Hired for what you're great at.", body: "Your skills help us put the right tasks in front of you first." },
    availability: { emoji: "🗓️", title: "On your schedule.", body: "Tell us when you're free so posters know you can show up." },
    travel:       { emoji: "🛵", title: "How far you'll go.", body: "We'll prioritise tasks within your reach — and flag the ones that need wheels." },
    bio:          { emoji: "✨", title: "Make a strong first impression.", body: "A photo and a line about you build trust with the people hiring." },
    basics:       { emoji: "✅", title: "Almost there.", body: "Once you're in, browse tasks or post your first one in under a minute." },
  };
  const panel = PANELS[key];

  const Chip = ({ active, onClick, children }) => (
    <button onClick={onClick} style={{
      padding: "10px 16px", borderRadius: 999, cursor: "pointer", fontFamily: "var(--sans)", fontSize: 14, fontWeight: 600,
      border: "1.5px solid " + (active ? "var(--clay)" : "var(--line)"),
      background: active ? "color-mix(in srgb, var(--clay) 8%, var(--surface))" : "var(--surface)",
      color: active ? "var(--ink)" : "var(--ink-2)", transition: "all .12s",
    }}>{children}</button>
  );

  const h2Style = { fontFamily: "var(--display)", fontWeight: 600, fontSize: "clamp(24px,3vw,34px)", letterSpacing: "-0.03em", margin: "0 0 8px", color: "var(--ink)", lineHeight: 1.15 };
  const subStyle = { margin: "0 0 24px", fontSize: 15.5, color: "var(--ink-2)", lineHeight: 1.5 };
  const fieldLabel = { fontSize: 13.5, fontWeight: 700, color: "var(--ink)", marginBottom: 8 };

  return (
    <div style={{ minHeight: "100vh", display: "flex", background: "var(--paper)" }}>

      {/* ── Left: form ── */}
      <div className="onboard-form" style={{ flex: 1, display: "flex", flexDirection: "column", padding: "36px 48px 48px", overflowY: "auto" }}>

        {/* header row */}
        <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between", marginBottom: 28 }}>
          <span style={{ display: "inline-flex", alignItems: "center", gap: 9 }}>
            <span style={{ width: 34, height: 34, borderRadius: 10, background: "var(--clay)", display: "grid", placeItems: "center" }}>
              <Icon name="users" size={18} stroke={2} style={{ color: "#fff" }} />
            </span>
            <span style={{ fontFamily: "var(--display)", fontWeight: 700, fontSize: 21, letterSpacing: "-0.03em", color: "var(--ink)" }}>TaskPe</span>
          </span>
          <span style={{ fontSize: 13, fontWeight: 600, color: "var(--ink-2)" }}>step {stepIdx + 1} of {total}</span>
        </div>

        {/* back */}
        {stepIdx > 0 && (
          <button onClick={() => { setStepIdx(i => Math.max(0, i - 1)); setError(""); }} style={{ display: "inline-flex", alignItems: "center", gap: 6, background: "none", border: "none", cursor: "pointer", color: "var(--ink-2)", fontFamily: "var(--sans)", fontSize: 13.5, fontWeight: 600, padding: 0, marginBottom: 18 }}>
            <Icon name="back" size={14} /> back
          </button>
        )}

        {/* progress bar */}
        <div style={{ height: 3, background: "var(--line)", borderRadius: 999, marginBottom: 32, overflow: "hidden" }}>
          <div style={{ height: "100%", width: `${((stepIdx + 1) / total) * 100}%`, background: "var(--clay)", borderRadius: 999, transition: "width .35s ease" }} />
        </div>

        <div style={{ flex: 1 }}>
          {/* ── role ── */}
          {key === "role" && (
            <>
              <h2 style={h2Style}>What brings you here?</h2>
              <p style={subStyle}>We'll tailor your experience around it.</p>
              <div style={{ display: "flex", flexDirection: "column", gap: 10 }}>
                {ROLES.map(r => (
                  <button key={r.id} onClick={() => setRole(r.id)} style={{
                    display: "flex", alignItems: "center", gap: 16, padding: "17px 20px",
                    borderRadius: 16, border: "2px solid " + (role === r.id ? "var(--clay)" : "var(--line)"),
                    background: role === r.id ? "color-mix(in srgb, var(--clay) 6%, var(--surface))" : "var(--surface)",
                    cursor: "pointer", textAlign: "left", transition: "border-color .15s, background .15s", width: "100%",
                  }}>
                    <span style={{ fontSize: 24, flexShrink: 0 }}>{r.emoji}</span>
                    <div style={{ flex: 1 }}>
                      <div style={{ fontFamily: "var(--sans)", fontWeight: 700, fontSize: 15, color: "var(--ink)", marginBottom: 2 }}>{r.title}</div>
                      <div style={{ fontFamily: "var(--sans)", fontSize: 13, color: "var(--ink-2)" }}>{r.sub}</div>
                    </div>
                    <div style={{ width: 20, height: 20, borderRadius: "50%", border: "2px solid " + (role === r.id ? "var(--clay)" : "var(--line-dk)"), background: role === r.id ? "var(--clay)" : "transparent", display: "grid", placeItems: "center", flexShrink: 0, transition: "all .15s" }}>
                      {role === r.id && <span style={{ width: 7, height: 7, borderRadius: "50%", background: "#fff" }} />}
                    </div>
                  </button>
                ))}
              </div>
            </>
          )}

          {/* ── categories ── */}
          {key === "categories" && (
            <>
              <h2 style={h2Style}>{role === "poster" ? "What kind of help do you need?" : "What tasks can you do?"}</h2>
              <p style={subStyle}>Pick everything that fits — this shapes what we show you.</p>
              <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 10 }}>
                {CATEGORIES.map(c => {
                  const sel = cats.has(c.id);
                  return (
                    <button key={c.id} onClick={() => toggleCat(c.id)} style={{
                      display: "flex", alignItems: "center", gap: 11, padding: "14px 15px",
                      borderRadius: 14, border: "2px solid " + (sel ? "var(--clay)" : "var(--line)"),
                      background: sel ? "color-mix(in srgb, var(--clay) 6%, var(--surface))" : "var(--surface)",
                      cursor: "pointer", textAlign: "left", transition: "border-color .15s, background .15s",
                    }}>
                      <Icon name={c.icon} size={17} style={{ color: sel ? "var(--clay)" : "var(--ink-2)", flexShrink: 0 }} />
                      <span style={{ fontFamily: "var(--sans)", fontWeight: 600, fontSize: 13.5, color: sel ? "var(--ink)" : "var(--ink-2)", flex: 1, lineHeight: 1.3 }}>{c.label}</span>
                      {sel && <Icon name="check" size={13} stroke={2.5} style={{ color: "var(--clay)", flexShrink: 0 }} />}
                    </button>
                  );
                })}
              </div>
            </>
          )}

          {/* ── skills ── */}
          {key === "skills" && (
            <>
              <h2 style={h2Style}>What are you great at?</h2>
              <p style={subStyle}>Add skills so we can match you to the right tasks. Type and press Enter, or tap a suggestion.</p>
              <input
                value={skillInput}
                onChange={e => setSkillInput(e.target.value)}
                onKeyDown={e => { if (e.key === "Enter") { e.preventDefault(); addSkill(); } }}
                placeholder="e.g. Photography, driving, cooking…"
                style={authInputStyle}
              />
              {skills.length > 0 && (
                <div style={{ display: "flex", flexWrap: "wrap", gap: 8, marginTop: 14 }}>
                  {skills.map(s => (
                    <span key={s} style={{ display: "inline-flex", alignItems: "center", gap: 7, padding: "8px 12px", borderRadius: 999, background: "var(--clay)", color: "#fff", fontSize: 13.5, fontWeight: 600 }}>
                      {s}
                      <button onClick={() => removeSkill(s)} style={{ background: "none", border: "none", color: "#fff", cursor: "pointer", padding: 0, display: "grid", placeItems: "center", opacity: 0.85 }}>✕</button>
                    </span>
                  ))}
                </div>
              )}
              <div style={{ fontSize: 12.5, fontWeight: 700, color: "var(--ink-2)", textTransform: "uppercase", letterSpacing: "0.05em", margin: "22px 0 10px" }}>Suggestions</div>
              <div style={{ display: "flex", flexWrap: "wrap", gap: 8 }}>
                {SKILL_SUGGEST.filter(s => !skills.includes(s)).map(s => (
                  <Chip key={s} active={false} onClick={() => addSkill(s)}>+ {s}</Chip>
                ))}
              </div>
            </>
          )}

          {/* ── availability ── */}
          {key === "availability" && (
            <>
              <h2 style={h2Style}>When are you free?</h2>
              <p style={subStyle}>This helps posters know when you can actually show up.</p>
              <div style={{ ...fieldLabel, marginBottom: 10 }}>Days & times</div>
              <div style={{ display: "flex", flexWrap: "wrap", gap: 8, marginBottom: 22 }}>
                {AVAIL_DAYS.map(([v, l]) => <Chip key={v} active={availDays.has(v)} onClick={() => toggleDay(v)}>{l}</Chip>)}
              </div>
              <div style={{ ...fieldLabel, marginBottom: 10 }}>Roughly how many hours a week?</div>
              <div style={{ display: "flex", flexWrap: "wrap", gap: 8 }}>
                {AVAIL_HOURS.map(([v, l]) => <Chip key={v} active={availHours === v} onClick={() => setAvailHours(availHours === v ? "" : v)}>{l} hrs</Chip>)}
              </div>
            </>
          )}

          {/* ── travel & transport ── */}
          {key === "travel" && (
            <>
              <h2 style={h2Style}>How far will you travel?</h2>
              <p style={subStyle}>We'll prioritise tasks within your reach.</p>
              <div style={{ ...fieldLabel, marginBottom: 10 }}>Travel radius</div>
              <div style={{ display: "flex", flexWrap: "wrap", gap: 8, marginBottom: 22 }}>
                {TRAVEL_RADII.map(([v, l]) => <Chip key={v} active={travel === v} onClick={() => setTravel(travel === v ? "" : v)}>{l}</Chip>)}
              </div>
              <div style={{ ...fieldLabel, marginBottom: 10 }}>Do you have a vehicle?</div>
              <div style={{ display: "flex", flexWrap: "wrap", gap: 8 }}>
                {VEHICLES.map(([v, l]) => <Chip key={v} active={vehicle === v} onClick={() => setVehicle(vehicle === v ? "" : v)}>{l}</Chip>)}
              </div>
            </>
          )}

          {/* ── bio & photo ── */}
          {key === "bio" && (
            <>
              <h2 style={h2Style}>Add a face and a few words</h2>
              <p style={subStyle}>Optional, but profiles with a photo and bio get hired more.</p>
              <div style={{ display: "flex", alignItems: "center", gap: 16, marginBottom: 20 }}>
                <label style={{ cursor: "pointer", display: "inline-block", position: "relative", flexShrink: 0 }}>
                  {photoPreview
                    ? <img src={photoPreview} alt="you" style={{ width: 84, height: 84, borderRadius: "50%", objectFit: "cover" }} />
                    : <div style={{ width: 84, height: 84, borderRadius: "50%", background: "var(--ink-3)", display: "grid", placeItems: "center", color: "var(--ink-2)" }}><Icon name="camera" size={26} /></div>}
                  <span style={{ position: "absolute", bottom: 0, right: 0, width: 28, height: 28, borderRadius: "50%", background: "var(--clay)", color: "#fff", border: "2px solid var(--paper)", display: "grid", placeItems: "center" }}><Icon name="plus" size={14} stroke={2.6} /></span>
                  <input type="file" accept="image/*" onChange={pickPhoto} style={{ display: "none" }} />
                </label>
                <div style={{ fontSize: 13.5, color: "var(--ink-2)", lineHeight: 1.5 }}>{photoPreview ? "Looking good! Tap to change." : "Add a clear photo of your face."}</div>
              </div>
              <div style={fieldLabel}>Short bio</div>
              <textarea value={bio} onChange={e => setBio(e.target.value)} rows={3} maxLength={240}
                placeholder="A line or two about you — what you're good at, why people should hire you…"
                style={{ ...authInputStyle, resize: "vertical", lineHeight: 1.5 }} />
              <div style={{ fontSize: 12, color: "var(--ink-2)", textAlign: "right", marginTop: 6 }}>{bio.length}/240</div>
            </>
          )}

          {/* ── basics ── */}
          {key === "basics" && (
            <>
              <h2 style={h2Style}>Last bit — the basics</h2>
              <p style={subStyle}>You can change any of this later in Settings.</p>
              <div style={{ display: "flex", flexDirection: "column", gap: 16 }}>
                <label>
                  <div style={fieldLabel}>Full name <span style={{ color: "var(--clay)" }}>*</span></div>
                  <input type="text" value={name} autoFocus onChange={e => { setName(e.target.value.slice(0, 50)); setError(""); }} placeholder="Your name" autoComplete="name" maxLength={50} style={authInputStyle} />
                </label>
                <label>
                  <div style={fieldLabel}>City <span style={{ color: "var(--clay)" }}>*</span></div>
                  <input type="text" value={city} onChange={e => { setCity(e.target.value.slice(0, 50)); setError(""); }} placeholder="e.g. Hyderabad, Mumbai, Bangalore" maxLength={50} style={authInputStyle} />
                </label>
                 <label>
                  <div style={fieldLabel}>Phone number <span style={{ color: "var(--clay)" }}>*</span></div>
                  <input type="tel" value={phone} onChange={e => { 
                    const val = e.target.value;
                    if (/\D/.test(val)) setError("Phone number can only contain numbers.");
                    else setError("");
                    const digits = val.replace(/\D/g, "").slice(0, 10); setPhone(digits); 
                  }} onKeyDown={e => e.key === "Enter" && submit()} placeholder="9876543210" autoComplete="tel" inputMode="numeric" maxLength={10} style={authInputStyle} />
                  <div style={{ fontSize: 12.5, color: phone.length > 0 && phone.length < 10 ? "var(--clay)" : "var(--ink-2)", marginTop: 6 }}>{phone.length > 0 ? `${phone.length}/10 digits` : "10-digit mobile number (without +91)"}</div>
                </label>
              </div>
              {error && <div style={{ marginTop: 14 }}><ErrMsg text={error} /></div>}
            </>
          )}
        </div>

        {/* unified bottom action */}
        <Button full size="lg" icon={isLast ? "check" : undefined} onClick={next} disabled={!canNext() || loading} style={{ marginTop: 26 }}>
          {btnLabel}
        </Button>
      </div>

      {/* ── Right: accent panel ── */}
      <div className="onboard-panel" style={{ flexShrink: 0, width: 380, background: "var(--clay)", display: "flex", flexDirection: "column", alignItems: "flex-start", justifyContent: "flex-end", padding: 48, position: "sticky", top: 0, height: "100vh" }}>
        <div style={{ color: "#fff" }}>
          <OnboardingGraphic step={key} />
          <div style={{ fontFamily: "var(--display)", fontSize: 24, fontWeight: 600, lineHeight: 1.3, marginBottom: 12 }}>{panel.title}</div>
          <div style={{ fontSize: 15, opacity: 0.75, lineHeight: 1.65 }}>{panel.body}</div>
        </div>
      </div>

    </div>
  );
}

/* ── Reset password screen (after clicking the reset link) ─── */
function ResetPasswordScreen({ onDone }) {
  const [password, setPassword] = useAuth("");
  const [confirm, setConfirm] = useAuth("");
  const [show, setShow] = useAuth(false);
  const [loading, setLoading] = useAuth(false);
  const [error, setError] = useAuth("");

  const submit = async () => {
    if (password.length < 6) { setError("Password must be at least 6 characters."); return; }
    if (password !== confirm) { setError("Passwords don't match."); return; }
    setLoading(true); setError("");
    const { error: e } = await Auth.updatePassword(password);
    setLoading(false);
    if (e) { setError(prettyAuthError(e)); return; }
    onDone();
  };

  return (
    <div style={{ minHeight: "100vh", display: "flex", alignItems: "center", justifyContent: "center", background: "var(--paper)", padding: 24 }}>
      <div style={{ width: "100%", maxWidth: 420 }}>
        <div style={{ textAlign: "center", marginBottom: 40 }}>
          <span style={{ display: "inline-flex", alignItems: "center", gap: 10 }}>
            <span style={{ width: 40, height: 40, borderRadius: 12, background: "var(--clay)", display: "grid", placeItems: "center" }}>
              <Icon name="users" size={22} stroke={2} style={{ color: "#fff" }} />
            </span>
            <span style={{ fontFamily: "var(--display)", fontWeight: 700, fontSize: 26, letterSpacing: "-0.03em", color: "var(--ink)" }}>TaskPe</span>
          </span>
        </div>
        <div style={{ background: "var(--surface)", border: "1px solid var(--line)", borderRadius: 24, padding: 32 }}>
          <h2 style={{ fontFamily: "var(--display)", fontWeight: 600, fontSize: 28, letterSpacing: "-0.03em", margin: "0 0 6px", color: "var(--ink)" }}>Set a new password</h2>
          <p style={{ margin: "0 0 28px", fontSize: 15.5, color: "var(--ink-2)", lineHeight: 1.5 }}>Choose a new password for your account.</p>

          <label style={{ display: "block", marginBottom: 16 }}>
            <div style={{ fontSize: 13.5, fontWeight: 700, color: "var(--ink)", marginBottom: 8 }}>New password</div>
            <div style={{ position: "relative", display: "flex", alignItems: "center" }}>
              <input type={show ? "text" : "password"} value={password}
                onChange={e => { setPassword(e.target.value); setError(""); }}
                placeholder="At least 6 characters" autoComplete="new-password"
                style={{ ...authInputStyle, paddingRight: 64 }} />
              <button onClick={() => setShow(s => !s)} type="button" style={{ position: "absolute", right: 12, background: "none", border: "none", cursor: "pointer", color: "var(--ink-2)", fontFamily: "var(--sans)", fontSize: 13, fontWeight: 600 }}>
                {show ? "Hide" : "Show"}
              </button>
            </div>
          </label>

          <label style={{ display: "block", marginBottom: 20 }}>
            <div style={{ fontSize: 13.5, fontWeight: 700, color: "var(--ink)", marginBottom: 8 }}>Confirm password</div>
            <input type={show ? "text" : "password"} value={confirm}
              onChange={e => { setConfirm(e.target.value); setError(""); }}
              onKeyDown={e => e.key === "Enter" && submit()}
              placeholder="Re-enter your password" autoComplete="new-password"
              style={authInputStyle} />
          </label>

          {error && <ErrMsg text={error} />}

          <Button full size="lg" icon="check" onClick={submit} disabled={loading}>
            {loading ? "Saving…" : "Update password"}
          </Button>
        </div>
      </div>
    </div>
  );
}

const linkBtn = { background: "none", border: "none", cursor: "pointer", color: "var(--clay)", fontWeight: 700, fontFamily: "var(--sans)", fontSize: 14, padding: 0 };

function prettyAuthError(msg) {
  const m = (msg || "").toLowerCase();
  if (m.includes("already registered") || m.includes("already exists") || m.includes("already been registered")) return "That email already has an account — switch to Sign in.";
  if (m.includes("invalid login") || m.includes("invalid credentials")) return "Wrong email or password.";
  if (m.includes("email not confirmed") || m.includes("not confirmed")) return "Check your inbox and click the confirmation link first.";
  if (m.includes("rate limit") || m.includes("429")) return "Too many requests — rate-limited. Wait a bit.";
  if (m.includes("sending") || m.includes("smtp") || m.includes("sms")) return "Code couldn't send — check your provider configuration.";
  return msg;
}

/* ── ID Verification modal ─────────────────────────────────── */
function DocUpload({ label, hint, icon, preview, onPick, capture }) {
  return (
    <label style={{ display: "block", cursor: "pointer" }}>
      <div style={{ fontSize: 13.5, fontWeight: 700, color: "var(--ink)", marginBottom: 8 }}>{label}</div>
      <div style={{ border: "2px dashed var(--line-dk)", borderRadius: 14, padding: preview ? 8 : 20, textAlign: "center", background: preview ? "transparent" : "var(--ink-3)", overflow: "hidden" }}>
        {preview ? (
          <img src={preview} alt={label} style={{ maxWidth: "100%", maxHeight: 150, borderRadius: 8, objectFit: "contain" }} />
        ) : (
          <div>
            <Icon name={icon} size={28} style={{ color: "var(--ink-2)", marginBottom: 8 }} />
            <div style={{ fontSize: 14, fontWeight: 600, color: "var(--ink-2)" }}>Tap to upload</div>
            <div style={{ fontSize: 12.5, color: "var(--ink-2)", marginTop: 3 }}>{hint}</div>
          </div>
        )}
      </div>
      <input type="file" accept="image/*" {...(capture ? { capture: "user" } : {})} onChange={onPick} style={{ display: "none" }} />
    </label>
  );
}

function IDVerifyModal({ userId, onClose, onSubmit }) {
  const [idFile, setIdFile] = useAuth(null);
  const [idPreview, setIdPreview] = useAuth(null);
  const [selfieFile, setSelfieFile] = useAuth(null);
  const [selfiePreview, setSelfiePreview] = useAuth(null);
  const [uploading, setUploading] = useAuth(false);
  const [error, setError] = useAuth("");

  const pickId = (e) => { const f = e.target.files[0]; if (!f) return; setIdFile(f); setIdPreview(URL.createObjectURL(f)); setError(""); };
  const pickSelfie = (e) => { const f = e.target.files[0]; if (!f) return; setSelfieFile(f); setSelfiePreview(URL.createObjectURL(f)); setError(""); };

  const submit = async () => {
    if (!idFile) { setError("Please upload a photo of your ID."); return; }
    if (!selfieFile) { setError("Please add a selfie so we can match it to your ID."); return; }
    setUploading(true); setError("");
    const idRes = await Profiles.uploadDoc(userId, idFile, "id");
    if (idRes.error) { setError(idRes.error); setUploading(false); return; }
    const selfieRes = await Profiles.uploadDoc(userId, selfieFile, "selfie");
    if (selfieRes.error) { setError(selfieRes.error); setUploading(false); return; }
    await Profiles.upsert(userId, { id_photo_url: idRes.path, selfie_url: selfieRes.path, verification_status: "pending", reject_reason: null });
    setUploading(false);
    onSubmit({ idUrl: idPreview, selfieUrl: selfiePreview });
  };

  return (
    <div onClick={onClose} style={modalOverlay}>
      <div onClick={e => e.stopPropagation()} style={{ ...modalCard, maxWidth: 480 }}>
        <div style={{ padding: "22px 26px", borderBottom: "1px solid var(--line)", display: "flex", justifyContent: "space-between", alignItems: "center" }}>
          <h2 style={{ fontFamily: "var(--display)", fontWeight: 600, fontSize: 22, letterSpacing: "-0.02em", margin: 0, color: "var(--ink)" }}>Verify your identity</h2>
          <button onClick={onClose} style={closeBtn}>✕</button>
        </div>
        <div style={{ padding: "22px 26px", display: "flex", flexDirection: "column", gap: 18 }}>
          <p style={{ margin: 0, fontSize: 14.5, color: "var(--ink-2)", lineHeight: 1.5 }}>
            We check that your ID is real and that it's actually you. Your documents are private and only seen by our review team.
          </p>
          <DocUpload label="1. Photo of your ID" hint="Aadhaar, PAN, or driving licence" icon="doc" preview={idPreview} onPick={pickId} />
          <DocUpload label="2. A selfie" hint="A clear photo of your face" icon="camera" preview={selfiePreview} onPick={pickSelfie} capture />
          {error && <ErrMsg text={error} />}
        </div>
        <div style={{ padding: "18px 26px", borderTop: "1px solid var(--line)", display: "flex", gap: 10, justifyContent: "flex-end" }}>
          <Button variant="ghost" onClick={onClose}>Later</Button>
          <Button icon="shield" onClick={submit} disabled={uploading || !idFile || !selfieFile}>
            {uploading ? "Uploading…" : "Submit for review"}
          </Button>
        </div>
      </div>
    </div>
  );
}

function ErrMsg({ text }) {
  return (
    <div style={{ color: "var(--clay)", fontSize: 14, fontWeight: 600, display: "flex", gap: 7, alignItems: "flex-start", marginBottom: 14, lineHeight: 1.4 }}>
      <Icon name="bolt" size={15} style={{ flexShrink: 0, marginTop: 1 }} /> {text}
    </div>
  );
}

const authInputStyle = { width: "100%", padding: "13px 15px", borderRadius: 12, border: "1px solid var(--line)", background: "var(--paper)", fontFamily: "var(--sans)", fontSize: 16, color: "var(--ink)", outline: "none", boxSizing: "border-box" };

/* ── Settings page ─────────────────────────────────────────── */
function SettingsPage({ go, profile, email, demoMode, verification, rejectReason, onSave, onVerify, onLogout, canLogout, dark, onToggleDark }) {
  const me = profile || ME;
  const [name, setName] = useAuth(me.name === "You" ? "" : (me.name || ""));
  const [city, setCity] = useAuth(me.city || "");
  const [phone, setPhone] = useAuth(me.phone || "");
  const [error, setError] = useAuth("");
  const [saving, setSaving] = useAuth(false);
  const [saved, setSavedFlag] = useAuth(false);

  const save = async () => {
    if (!name.trim()) { setError("Name is required."); return; }
    if (!phone.trim()) { setError("Phone number is required so that users can contact you for tasks."); return; }
    if (phone.replace(/\D/g, "").length !== 10) { setError("Phone number must be exactly 10 digits."); return; }
    if (!city.trim()) { setError("City is required."); return; }
    setError("");
    setSaving(true); setSavedFlag(false);
    await onSave({ name: name.trim() || me.name, city: city.trim(), phone: phone.trim() });
    setSaving(false); setSavedFlag(true);
    setTimeout(() => setSavedFlag(false), 2500);
  };

  const vStatus = verification || "unverified";
  const vMap = {
    verified:   { l: "Verified", c: "var(--green)", bg: "var(--green-3)" },
    pending:    { l: "Under review", c: "var(--amber-dk)", bg: "color-mix(in srgb, var(--amber) 16%, transparent)" },
    rejected:   { l: "Rejected", c: "var(--clay)", bg: "color-mix(in srgb, var(--clay) 12%, transparent)" },
    unverified: { l: "Not verified", c: "var(--ink-2)", bg: "var(--ink-3)" },
  }[vStatus];

  return (
    <Wrap style={{ paddingTop: 32, paddingBottom: 40, maxWidth: 640 }}>
      <button onClick={() => go("dashboard")} style={{ display: "inline-flex", alignItems: "center", gap: 7, background: "none", border: "none", cursor: "pointer", color: "var(--ink-2)", fontFamily: "var(--sans)", fontSize: 14.5, fontWeight: 600, padding: "8px 0", marginBottom: 12 }}>
        <Icon name="back" size={17} /> Back
      </button>

      <h1 style={{ fontFamily: "var(--display)", fontWeight: 600, fontSize: "clamp(26px,3.5vw,38px)", letterSpacing: "-0.03em", margin: "0 0 24px", color: "var(--ink)" }}>Settings</h1>

      {/* profile */}
      <div style={settingsCard}>
        <div style={settingsHead}>Profile</div>
        <div style={{ display: "flex", alignItems: "center", gap: 14, marginBottom: 20 }}>
          <Avatar name={name || me.name || "You"} size={56} />
          <div>
            <div style={{ fontWeight: 700, fontSize: 16, color: "var(--ink)" }}>{name || me.name}</div>
            {email && <div style={{ fontSize: 13.5, color: "var(--ink-2)", marginTop: 2 }}>{email}</div>}
          </div>
        </div>
        {error && <ErrMsg text={error} />}
        <Field label="Name"><input value={name} onChange={e => { setName(e.target.value.slice(0, 50)); setError(""); }} placeholder="Your name" maxLength={50} style={inputStyle} /></Field>
        <div style={{ height: 16 }} />
        <Field label="Phone number">
          <input type="tel" value={phone} onChange={e => { 
            const val = e.target.value;
            if (/\D/.test(val)) setError("Phone number can only contain numbers.");
            else setError("");
            const digits = val.replace(/\D/g, "").slice(0, 10); setPhone(digits); 
          }} placeholder="9876543210" inputMode="numeric" maxLength={10} style={inputStyle} />
          <div style={{ fontSize: 12.5, color: phone.length > 0 && phone.length < 10 ? "var(--clay)" : "var(--ink-2)", marginTop: 6 }}>{phone.length > 0 ? `${phone.length}/10 digits` : "10-digit mobile number (without +91)"}</div>
        </Field>
        <div style={{ height: 16 }} />
        <Field label="City"><input value={city} onChange={e => { setCity(e.target.value.slice(0, 50)); setError(""); }} placeholder="Your city" maxLength={50} style={inputStyle} /></Field>
        <div style={{ display: "flex", alignItems: "center", gap: 12, marginTop: 20 }}>
          <Button icon="check" onClick={save} disabled={saving}>{saving ? "Saving…" : "Save changes"}</Button>
          {saved && <span style={{ fontSize: 14, fontWeight: 600, color: "var(--green)", display: "inline-flex", alignItems: "center", gap: 6 }}><Icon name="check" size={15} stroke={2.4} /> Saved</span>}
          {demoMode && <span style={{ fontSize: 12.5, color: "var(--ink-2)" }}>(demo — not saved to a database)</span>}
        </div>
      </div>

      {/* verification */}
      <div style={settingsCard}>
        <div style={settingsHead}>Identity verification</div>
        <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between", gap: 14, flexWrap: "wrap" }}>
          <div style={{ display: "flex", alignItems: "center", gap: 10 }}>
            <span style={{ fontSize: 13, fontWeight: 700, color: vMap.c, background: vMap.bg, padding: "5px 13px", borderRadius: 999 }}>{vMap.l}</span>
            <span style={{ fontSize: 13.5, color: "var(--ink-2)" }}>Needed to take paid tasks.</span>
          </div>
          {(vStatus === "unverified" || vStatus === "rejected") && <Button size="sm" icon="shield" onClick={onVerify}>{vStatus === "rejected" ? "Re-submit" : "Verify now"}</Button>}
        </div>
        {vStatus === "rejected" && rejectReason && (
          <div style={{ marginTop: 14, background: "color-mix(in srgb, var(--clay) 8%, transparent)", border: "1px solid color-mix(in srgb, var(--clay) 22%, transparent)", borderRadius: 12, padding: "12px 14px", fontSize: 14, color: "var(--ink)", lineHeight: 1.5 }}>
            <strong style={{ color: "var(--clay)" }}>Why it was rejected:</strong> {rejectReason}
          </div>
        )}
        {vStatus === "pending" && (
          <div style={{ marginTop: 12, fontSize: 13.5, color: "var(--ink-2)", lineHeight: 1.5 }}>
            Your documents are under review — this usually takes a few hours.
          </div>
        )}
      </div>

      {/* payment methods */}
      <div style={settingsCard}>
        <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center", marginBottom: 18 }}>
          <div style={{ ...settingsHead, marginBottom: 0 }}>Payment methods</div>
          <Button variant="ghost" size="sm" icon="plus">Add</Button>
        </div>
        <div style={{ display: "flex", flexDirection: "column", gap: 12 }}>
          {MY_PAYMENTS.map((pm) => (
            <div key={pm.id} style={{ display: "flex", alignItems: "center", gap: 14, padding: "14px 16px", borderRadius: 12, border: "1px solid var(--line)", background: "var(--paper)" }}>
              <span style={{ width: 40, height: 40, borderRadius: 10, background: "var(--ink-3)", display: "grid", placeItems: "center", color: "var(--ink-2)" }}>
                <Icon name="wallet" size={20} />
              </span>
              <div style={{ flex: 1 }}>
                <div style={{ fontWeight: 600, fontSize: 15, color: "var(--ink)" }}>{pm.type}</div>
                <div style={{ fontSize: 13.5, color: "var(--ink-2)" }}>{pm.label}</div>
              </div>
              {pm.primary && <span style={{ fontSize: 12, fontWeight: 700, color: "var(--green)", background: "var(--green-3)", padding: "3px 10px", borderRadius: 999 }}>Primary</span>}
            </div>
          ))}
        </div>
      </div>

      {/* linked accounts */}
      <div style={settingsCard}>
        <div style={settingsHead}>Linked accounts</div>
        <div style={{ display: "flex", flexDirection: "column", gap: 12 }}>
          {MY_LINKED.map((la) => (
            <div key={la.provider} style={{ display: "flex", alignItems: "center", gap: 14, padding: "14px 16px", borderRadius: 12, border: "1px solid var(--line)", background: "var(--paper)" }}>
              <span style={{ width: 40, height: 40, borderRadius: 10, background: "var(--ink-3)", display: "grid", placeItems: "center", color: "var(--ink-2)" }}>
                <Icon name={la.provider === "Google" ? "mail" : "phone"} size={20} />
              </span>
              <div style={{ flex: 1 }}>
                <div style={{ fontWeight: 600, fontSize: 15, color: "var(--ink)" }}>{la.provider}</div>
                <div style={{ fontSize: 13.5, color: "var(--ink-2)" }}>{la.email || la.value}</div>
              </div>
              <span style={{ fontSize: 13, fontWeight: 600, color: "var(--green)", display: "inline-flex", alignItems: "center", gap: 5 }}><Icon name="check" size={14} stroke={2.4} /> Connected</span>
            </div>
          ))}
        </div>
      </div>

      {/* preferences */}
      <div style={settingsCard}>
        <div style={settingsHead}>Preferences</div>
        <label style={{ display: "flex", alignItems: "center", justifyContent: "space-between", cursor: "pointer" }}>
          <span style={{ fontSize: 15, fontWeight: 600, color: "var(--ink)" }}>Dark mode</span>
          <span onClick={() => onToggleDark(!dark)} style={{ width: 46, height: 27, borderRadius: 999, background: dark ? "var(--clay)" : "var(--line-dk)", position: "relative", transition: "background .2s", flexShrink: 0 }}>
            <span style={{ position: "absolute", top: 3, left: dark ? 22 : 3, width: 21, height: 21, borderRadius: "50%", background: "#fff", transition: "left .2s" }} />
          </span>
        </label>
      </div>

      {/* support */}
      <div style={settingsCard}>
        <div style={settingsHead}>Support</div>
        <div style={{ display: "flex", flexDirection: "column", gap: 12 }}>
          <div style={{ fontSize: 14.5, color: "var(--ink-2)" }}>Need help with a task, payment, or report?</div>
          <Button variant="ghost" icon="mail" onClick={() => window.location.href = "mailto:hiringahuman@gmail.com"} style={{ color: "var(--clay)", borderColor: "color-mix(in srgb, var(--clay) 35%, transparent)", width: "fit-content" }}>Contact Support</Button>
        </div>
      </div>

      {/* account */}
      {canLogout && (
        <div style={settingsCard}>
          <div style={settingsHead}>Account</div>
          <Button variant="ghost" icon="back" onClick={onLogout} style={{ color: "var(--clay)", borderColor: "color-mix(in srgb, var(--clay) 35%, transparent)" }}>Log out</Button>
        </div>
      )}
    </Wrap>
  );
}

const settingsCard = { background: "var(--surface)", border: "1px solid var(--line)", borderRadius: 18, padding: 24, marginBottom: 16 };
const settingsHead = { fontSize: 12.5, fontWeight: 700, textTransform: "uppercase", letterSpacing: "0.06em", color: "var(--ink-2)", marginBottom: 16 };

Object.assign(window, { AuthGate, OnboardingForm, ResetPasswordScreen, IDVerifyModal, SettingsPage });
