// screens-verify.jsx — Premium user verification flow
const { useState: useV1, useEffect: useVE, useRef: useVR } = React;

const VERIFY_STEPS = [
  { key: "phone",   label: "Phone",   icon: "chat" },
  { key: "aadhaar", label: "Aadhaar", icon: "shield" },
  { key: "selfie",  label: "Selfie",  icon: "camera" },
  { key: "video",   label: "Video",   icon: "image" },
  { key: "upi",     label: "UPI",     icon: "wallet" },
  { key: "review",  label: "Review",  icon: "check" },
];

function VerifyFlow({ go, onComplete }) {
  const [step, setStep] = useV1(0);
  const [done, setDone] = useV1(false);
  const [data, setData] = useV1({
    phone: "", phoneVerified: false, otpSent: false,
    aadhaarName: "", aadhaarNumber: "",
    idType: "aadhaar", idFile: null, idFileName: "", idPreview: null,
    selfieFile: null, selfieFileName: "", selfiePreview: null,
    videoFile: null, videoFileName: "", videoPreview: null,
    upiId: "", upiNameConfirm: false, upiVerified: false, upiRegisteredName: "", consent: false,
  });
  const set = (k, v) => setData((s) => ({ ...s, [k]: v }));

  const canNext = () => {
    if (step === 0) return data.phone.replace(/\D/g, "").length >= 10 && data.phoneVerified;
    if (step === 1) return !!data.idFileName && data.aadhaarName.trim().length > 1 && data.aadhaarNumber.replace(/\D/g, "").length === 4;
    if (step === 2) return !!data.selfieFileName;
    if (step === 3) return !!data.videoFileName;
    if (step === 4) return /^[\w.\-]{2,}@[a-zA-Z]{2,}$/.test(data.upiId.trim()) && data.upiNameConfirm && data.consent;
    if (step === 5) return true; // review step
    return false;
  };

  const next = () => {
    if (step < 5) setStep(step + 1);
    else { setDone(true); onComplete && onComplete(data); }
  };

  if (done) {
    return (
      <Wrap style={{ paddingTop: 60, paddingBottom: 60, maxWidth: 560 }}>
        <div style={{ textAlign: "center" }}>
          <div style={{ width: 88, height: 88, borderRadius: "50%", background: "var(--green-3)", color: "var(--green)", display: "grid", placeItems: "center", margin: "0 auto 24px", animation: "scaleIn .4s ease" }}>
            <Icon name="shield" size={42} stroke={1.8} />
          </div>
          <h1 style={{ fontFamily: "var(--display)", fontWeight: 600, fontSize: 34, letterSpacing: "-0.03em", margin: "0 0 10px", color: "var(--ink)" }}>Verification submitted!</h1>
          <p style={{ fontSize: 17, color: "var(--ink-2)", lineHeight: 1.55, margin: "0 0 12px", maxWidth: 420, marginLeft: "auto", marginRight: "auto" }}>
            We'll review your documents and get back to you within 24 hours. You'll get a notification once approved.
          </p>
          <div style={{ display: "inline-flex", alignItems: "center", gap: 8, padding: "10px 18px", borderRadius: 999, background: "var(--ink-3)", fontSize: 14, fontWeight: 600, color: "var(--ink-2)", marginBottom: 32 }}>
            <Icon name="clock" size={15} /> Estimated: 2–24 hours
          </div>
          <div style={{ display: "flex", gap: 12, justifyContent: "center" }}>
            <Button variant="ghost" onClick={() => go("profile")}>Back to profile</Button>
            <Button onClick={() => go("home")}>Browse tasks</Button>
          </div>
        </div>
      </Wrap>
    );
  }

  return (
    <Wrap style={{ paddingTop: 28, paddingBottom: 40, maxWidth: 620 }}>
      <button onClick={() => (step === 0 ? go("profile") : setStep(step - 1))} 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: 16 }}>
        <Icon name="back" size={17} /> {step === 0 ? "Back to profile" : "Back"}
      </button>

      {/* Trust banner — only on first step */}
      {step === 0 && (
        <div style={{
          display: "flex", gap: 14, padding: "16px 18px", borderRadius: 14, marginBottom: 24,
          background: "linear-gradient(135deg, color-mix(in srgb, var(--green) 8%, transparent), color-mix(in srgb, var(--blue) 6%, transparent))",
          border: "1px solid color-mix(in srgb, var(--green) 18%, transparent)",
        }}>
          <div style={{ width: 42, height: 42, borderRadius: 12, background: "var(--green-3)", color: "var(--green)", display: "grid", placeItems: "center", flexShrink: 0 }}>
            <Icon name="shield" size={22} />
          </div>
          <div>
            <div style={{ fontWeight: 700, fontSize: 15, color: "var(--ink)", marginBottom: 4 }}>Your data is safe with us</div>
            <div style={{ fontSize: 13.5, color: "var(--ink-2)", lineHeight: 1.5 }}>
              Documents are encrypted, stored securely, and never shared. Only our review team sees them — and only to verify your identity.
            </div>
          </div>
        </div>
      )}

      <h1 style={{ fontFamily: "var(--display)", fontWeight: 600, fontSize: "clamp(26px,4vw,34px)", letterSpacing: "-0.03em", margin: "0 0 6px", color: "var(--ink)" }}>Verify your identity</h1>
      <p style={{ fontSize: 15.5, color: "var(--ink-2)", margin: "0 0 24px", lineHeight: 1.5 }}>
        Complete these steps to unlock paid tasks and start earning.
      </p>

      {/* Stepper */}
      <div style={{ display: "flex", gap: 4, marginBottom: 28 }}>
        {VERIFY_STEPS.map((s, i) => {
          const isComplete = i < step;
          const isCurrent = i === step;
          return (
            <div key={s.key} style={{ flex: 1, cursor: i <= step ? "pointer" : "default" }} onClick={() => { if (i < step) setStep(i); }}>
              <div style={{
                height: 5, borderRadius: 999, transition: "background .3s, box-shadow .3s",
                background: isComplete ? "var(--green)" : isCurrent ? "var(--clay)" : "var(--line)",
                boxShadow: isCurrent ? "0 0 8px color-mix(in srgb, var(--clay) 40%, transparent)" : "none",
              }} />
              <div style={{ display: "flex", alignItems: "center", gap: 5, marginTop: 8 }}>
                {isComplete ? (
                  <span style={{ color: "var(--green)", display: "flex" }}><Icon name="check" size={13} stroke={2.6} /></span>
                ) : (
                  <Icon name={s.icon} size={13} style={{ color: isCurrent ? "var(--clay)" : "var(--line-dk)" }} />
                )}
                <span style={{
                  fontSize: 12, fontWeight: 700,
                  color: isComplete ? "var(--green)" : isCurrent ? "var(--ink)" : "var(--ink-2)",
                }}>{s.label}</span>
              </div>
            </div>
          );
        })}
      </div>

      {/* Step content card */}
      <div style={{ background: "var(--surface)", border: "1px solid var(--line)", borderRadius: 20, padding: "clamp(24px,4vw,32px)", transition: "all .2s" }}>
        {step === 0 && <PhoneStep data={data} set={set} />}
        {step === 1 && <AadhaarStep data={data} set={set} />}
        {step === 2 && <SelfieStep data={data} set={set} />}
        {step === 3 && <VideoStep data={data} set={set} />}
        {step === 4 && <UpiStep data={data} set={set} />}
        {step === 5 && <ReviewStep data={data} setStep={setStep} />}
      </div>

      <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center", gap: 10, marginTop: 24 }}>
        <span style={{ fontSize: 13.5, color: "var(--ink-2)", fontWeight: 600 }}>
          Step {step + 1} of {VERIFY_STEPS.length}
        </span>
        <Button size="lg" iconRight={step < 5 ? "arrow" : "check"} disabled={!canNext()} onClick={next}>
          {step < 5 ? "Continue" : "Submit verification"}
        </Button>
      </div>
    </Wrap>
  );
}

/* ============ STEP 0: PHONE ============ */
function PhoneStep({ data, set }) {
  const [otp, setOtp] = useV1("");
  const [otpSending, setOtpSending] = useV1(false);
  const [otpVerifying, setOtpVerifying] = useV1(false);
  const [otpError, setOtpError] = useV1("");
  const phoneClean = data.phone.replace(/\D/g, "");
  const phoneValid = phoneClean.length >= 10;

  return (
    <div>
      <StepIcon icon="chat" />
      <h2 style={vStepTitle}>Add your phone number</h2>
      <p style={vStepSub}>This is how task posters will contact you. Ensure it is correct.</p>

      <div style={{ marginTop: 22, display: "flex", flexDirection: "column", gap: 16 }}>
        <div>
          <div style={{ fontSize: 14.5, fontWeight: 700, color: "var(--ink)", marginBottom: 8 }}>Phone number <span style={{ color: "var(--clay)" }}>*</span></div>
          <div style={{ display: "flex", gap: 10 }}>
            <div style={{ ...inputStyle, width: 70, display: "flex", alignItems: "center", justifyContent: "center", fontWeight: 700, color: "var(--ink-2)", flexShrink: 0 }}>+91</div>
            <input
              value={data.phone}
              onChange={(e) => { set("phone", e.target.value.replace(/[^\d\s]/g, "").slice(0, 12)); set("phoneVerified", false); }}
              placeholder="98765 43210"
              inputMode="tel" autoComplete="tel"
              disabled={data.phoneVerified}
              style={{ ...inputStyle, flex: 1, fontWeight: 600, fontSize: 17, letterSpacing: "0.03em" }}
            />
          </div>
        </div>

        {data.phoneVerified ? (
          <div style={{ display: "flex", alignItems: "center", gap: 10, padding: "14px 18px", borderRadius: 13, background: "var(--green-3)", border: "1px solid color-mix(in srgb, var(--green) 25%, transparent)" }}>
            <Icon name="check" size={20} stroke={2.4} style={{ color: "var(--green)" }} />
            <div>
              <div style={{ fontWeight: 700, fontSize: 15, color: "var(--green)" }}>Number saved</div>
              <div style={{ fontSize: 13, color: "var(--ink-2)", marginTop: 2 }}>+91 {data.phone}</div>
            </div>
            <button onClick={() => set("phoneVerified", false)} style={{ marginLeft: "auto", background: "none", border: "none", cursor: "pointer", color: "var(--ink-2)", fontSize: 13, fontWeight: 600, fontFamily: "var(--sans)" }}>Change</button>
          </div>
        ) : (
          <Button onClick={() => set("phoneVerified", true)} disabled={!phoneValid} size="md" style={{ alignSelf: "flex-start" }}>
            Confirm Number
          </Button>
        )}
      </div>
    </div>
  );
}

/* ============ STEP 1: AADHAAR ============ */
function AadhaarStep({ data, set }) {
  const digits4 = data.aadhaarNumber.replace(/\D/g, "");
  return (
    <div>
      <StepIcon icon="shield" />
      <h2 style={vStepTitle}>Upload your Aadhaar card</h2>
      <p style={vStepSub}>A clear photo of your Aadhaar. It's stored privately and seen only by our review team.</p>

      {/* Photo guidelines */}
      <div style={{ marginTop: 18, padding: "14px 16px", borderRadius: 13, background: "var(--ink-3)", border: "1px solid var(--line)" }}>
        <div style={{ fontSize: 13, fontWeight: 700, color: "var(--ink)", marginBottom: 10, display: "flex", alignItems: "center", gap: 6 }}>
          <Icon name="eye" size={14} /> Photo guidelines
        </div>
        <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 8 }}>
          {[
            ["check", "Flat surface, well-lit", "var(--green)"],
            ["check", "All 4 corners visible", "var(--green)"],
            ["ban", "No blurry or cropped images", "var(--clay)"],
            ["ban", "No screenshots of photos", "var(--clay)"],
          ].map(([icon, text, color], i) => (
            <div key={i} style={{ display: "flex", alignItems: "center", gap: 7, fontSize: 12.5, color: "var(--ink-2)" }}>
              <Icon name={icon} size={13} stroke={2} style={{ color, flexShrink: 0 }} /> {text}
            </div>
          ))}
        </div>
      </div>

      <div style={{ marginTop: 20, display: "flex", flexDirection: "column", gap: 16 }}>
        <div>
          <div style={{ fontSize: 14.5, fontWeight: 700, color: "var(--ink)", marginBottom: 8 }}>Full name as printed on Aadhaar <span style={{ color: "var(--clay)" }}>*</span></div>
          <input value={data.aadhaarName} onChange={(e) => set("aadhaarName", e.target.value)} placeholder="e.g. Arjun Rao" autoComplete="name" style={inputStyle} />
          <div style={{ fontSize: 12.5, color: data.aadhaarName.trim().length > 0 && data.aadhaarName.trim().length <= 1 ? "var(--clay)" : "var(--ink-2)", marginTop: 6 }}>Must match the name on your Aadhaar exactly. Your UPI must later match this name.</div>
        </div>
        <div>
          <div style={{ fontSize: 14.5, fontWeight: 700, color: "var(--ink)", marginBottom: 8 }}>Last 4 digits of Aadhaar <span style={{ color: "var(--clay)" }}>*</span></div>
          <input value={data.aadhaarNumber} onChange={(e) => set("aadhaarNumber", e.target.value.replace(/[^\d]/g, "").slice(0, 4))} placeholder="1234" inputMode="numeric" maxLength={4} style={{ ...inputStyle, maxWidth: 140, letterSpacing: "0.2em", fontWeight: 700, fontSize: 18, textAlign: "center" }} />
          <div style={{ fontSize: 12.5, color: digits4.length > 0 && digits4.length < 4 ? "var(--clay)" : "var(--ink-2)", marginTop: 6 }}>{digits4.length > 0 ? `${digits4.length}/4 digits` : "We store only the last 4 digits for verification."}</div>
        </div>
        <UploadZone fileName={data.idFileName} preview={data.idPreview} onUpload={(name, file) => { set("idFileName", name); set("idFile", file); set("idPreview", file ? URL.createObjectURL(file) : null); }} label="Upload Aadhaar photo" hint="JPG or PNG · Max 10MB" />
      </div>
    </div>
  );
}

/* ============ STEP 2: SELFIE ============ */
function SelfieStep({ data, set }) {
  return (
    <div>
      <StepIcon icon="camera" />
      <h2 style={vStepTitle}>Take a selfie</h2>
      <p style={vStepSub}>We'll match this against your Aadhaar photo. Make sure your face is clearly visible and well-lit.</p>

      {/* Do's and Don'ts */}
      <div style={{ marginTop: 18, display: "grid", gridTemplateColumns: "1fr 1fr", gap: 12 }}>
        <div style={{ padding: "14px 16px", borderRadius: 13, background: "var(--green-3)", border: "1px solid color-mix(in srgb, var(--green) 18%, transparent)" }}>
          <div style={{ fontSize: 12.5, fontWeight: 700, color: "var(--green)", marginBottom: 10, display: "flex", alignItems: "center", gap: 5 }}>
            <Icon name="check" size={13} stroke={2.4} /> Do's
          </div>
          {["Look straight at camera", "Good lighting on face", "Neutral expression", "Plain background"].map((t, i) => (
            <div key={i} style={{ fontSize: 12.5, color: "var(--ink-2)", marginBottom: 5, display: "flex", alignItems: "center", gap: 6 }}>
              <span style={{ width: 4, height: 4, borderRadius: "50%", background: "var(--green)", flexShrink: 0 }} /> {t}
            </div>
          ))}
        </div>
        <div style={{ padding: "14px 16px", borderRadius: 13, background: "color-mix(in srgb, var(--clay) 6%, transparent)", border: "1px solid color-mix(in srgb, var(--clay) 14%, transparent)" }}>
          <div style={{ fontSize: 12.5, fontWeight: 700, color: "var(--clay)", marginBottom: 10, display: "flex", alignItems: "center", gap: 5 }}>
            <Icon name="ban" size={13} stroke={2} /> Don'ts
          </div>
          {["No sunglasses or hats", "No face masks", "No group photos", "No heavy filters"].map((t, i) => (
            <div key={i} style={{ fontSize: 12.5, color: "var(--ink-2)", marginBottom: 5, display: "flex", alignItems: "center", gap: 6 }}>
              <span style={{ width: 4, height: 4, borderRadius: "50%", background: "var(--clay)", flexShrink: 0 }} /> {t}
            </div>
          ))}
        </div>
      </div>

      <div style={{ marginTop: 20 }}>
        <UploadZone fileName={data.selfieFileName} preview={data.selfiePreview} capture onUpload={(name, file) => { set("selfieFileName", name); set("selfieFile", file); set("selfiePreview", file ? URL.createObjectURL(file) : null); }} label="Take or upload a selfie" hint="Look straight at the camera · Well-lit" icon="camera" />
      </div>
    </div>
  );
}

/* ============ STEP 3: VIDEO ============ */
function VideoStep({ data, set }) {
  return (
    <div>
      <StepIcon icon="image" />
      <h2 style={vStepTitle}>Record a liveness video</h2>
      <p style={vStepSub}>A short clip proves it's really you — not just a photo of someone else's ID.</p>

      {/* Recording instructions */}
      <div style={{
        marginTop: 18, padding: "18px 20px", borderRadius: 14,
        background: "linear-gradient(135deg, color-mix(in srgb, var(--clay) 6%, transparent), color-mix(in srgb, var(--amber) 6%, transparent))",
        border: "1px solid color-mix(in srgb, var(--clay) 14%, transparent)",
      }}>
        <div style={{ fontSize: 14, fontWeight: 700, color: "var(--ink)", marginBottom: 12 }}>What to do in the video:</div>
        <div style={{ display: "flex", flexDirection: "column", gap: 10 }}>
          {[
            { num: "1", text: "Hold your phone at face level, look at the camera" },
            { num: "2", text: "Say your full name clearly" },
            { num: "3", text: "Say today's date" },
            { num: "4", text: "Turn your head left, then right slowly" },
          ].map(({ num, text }) => (
            <div key={num} style={{ display: "flex", gap: 11, alignItems: "flex-start" }}>
              <span style={{
                width: 24, height: 24, borderRadius: 999, flexShrink: 0,
                background: "var(--clay)", color: "#fff", fontSize: 12, fontWeight: 700,
                display: "grid", placeItems: "center",
              }}>{num}</span>
              <span style={{ fontSize: 14, color: "var(--ink)", lineHeight: 1.4, paddingTop: 2 }}>{text}</span>
            </div>
          ))}
        </div>
        <div style={{ marginTop: 14, fontSize: 13, color: "var(--ink-2)", display: "flex", alignItems: "center", gap: 7 }}>
          <Icon name="clock" size={14} /> 5–10 seconds is enough. Keep it simple.
        </div>
      </div>

      <div style={{ marginTop: 20 }}>
        <UploadZone accept="video/*" isVideo capture fileName={data.videoFileName} preview={data.videoPreview} icon="camera"
          onUpload={(name, file) => { set("videoFileName", name); set("videoFile", file); set("videoPreview", file ? URL.createObjectURL(file) : null); }}
          label="Record or upload a video" hint="MP4 or MOV · 5–10 seconds" />
      </div>
    </div>
  );
}

/* ============ STEP 4: UPI ============ */
function UpiStep({ data, set }) {
  const valid = /^[\w.\-]{2,}@[a-zA-Z]{2,}$/.test(data.upiId.trim());
  const [verifying, setVerifying] = useV1(false);
  const [upiResult, setUpiResult] = useV1(null);
  const [upiError, setUpiError] = useV1("");

  const verifyUpi = async () => {
    if (!valid || verifying) return;
    setVerifying(true);
    setUpiError("");
    setUpiResult(null);
    set("upiVerified", false);
    set("upiRegisteredName", "");

    try {
      const { data: result, error } = await Payments.verifyUPI(data.upiId.trim());
      if (error) { setUpiError(error); setVerifying(false); return; }
      setUpiResult(result);
      if (result.valid) {
        set("upiVerified", true);
        if (result.registered_name) set("upiRegisteredName", result.registered_name);
      } else {
        setUpiError("UPI ID is invalid or not recognized.");
      }
    } catch (e) { setUpiError(String(e.message || e)); }
    setVerifying(false);
  };

  const aadhaarName = (data.aadhaarName || "").trim().toLowerCase();
  const registeredName = (upiResult?.registered_name || data.upiRegisteredName || "").trim().toLowerCase();
  const nameMatch = registeredName && aadhaarName
    ? registeredName.includes(aadhaarName) || aadhaarName.includes(registeredName) : null;

  return (
    <div>
      <StepIcon icon="wallet" />
      <h2 style={vStepTitle}>Add your UPI ID</h2>
      <p style={vStepSub}>This is where you'll get paid. It must be registered in the same name as your Aadhaar.</p>
      <div style={{ marginTop: 20 }}>
        <div style={{ fontSize: 14.5, fontWeight: 700, color: "var(--ink)", marginBottom: 8 }}>UPI ID / VPA</div>
        <div style={{ display: "flex", gap: 10 }}>
          <input value={data.upiId} onChange={(e) => { set("upiId", e.target.value.trim()); set("upiVerified", false); setUpiResult(null); setUpiError(""); }}
            placeholder="yourname@okhdfcbank" style={{ ...inputStyle, flex: 1 }} />
          <Button onClick={verifyUpi} disabled={!valid || verifying} size="md">
            {verifying ? "Checking…" : data.upiVerified ? "Re-check" : "Verify UPI"}
          </Button>
        </div>
        {data.upiId && !valid && <div style={{ fontSize: 13, color: "var(--clay)", marginTop: 6, fontWeight: 600 }}>Enter a valid UPI ID (e.g. name@okaxis).</div>}

        {/* Popular UPI apps */}
        <div style={{ marginTop: 14, display: "flex", gap: 8, flexWrap: "wrap" }}>
          {["@okaxis", "@oksbi", "@okicici", "@okhdfc", "@paytm", "@ybl"].map(suffix => (
            <button key={suffix} onClick={() => { if (data.upiId && !data.upiId.includes("@")) set("upiId", data.upiId + suffix); }}
              style={{ padding: "5px 11px", borderRadius: 999, border: "1px solid var(--line)", background: "var(--surface)", fontFamily: "var(--sans)", fontSize: 12, fontWeight: 600, color: "var(--ink-2)", cursor: "pointer" }}>
              {suffix}
            </button>
          ))}
        </div>

        {upiResult && upiResult.valid && (
          <div style={{ marginTop: 14, padding: "14px 16px", borderRadius: 13, background: "var(--green-3)", border: "1px solid color-mix(in srgb, var(--green) 30%, transparent)" }}>
            <div style={{ display: "flex", alignItems: "center", gap: 8, color: "var(--green)", fontWeight: 700, fontSize: 14.5 }}>
              <Icon name="check" size={17} stroke={2.6} /> UPI ID verified
              {upiResult.mock && <span style={{ fontSize: 11, fontWeight: 500, color: "var(--ink-2)", marginLeft: 4 }}>(demo)</span>}
            </div>
            {upiResult.registered_name && (
              <div style={{ marginTop: 8, fontSize: 14, color: "var(--ink)", lineHeight: 1.4 }}>
                Registered to: <strong>{upiResult.registered_name}</strong>
              </div>
            )}
          </div>
        )}

        {upiResult?.valid && nameMatch !== null && (
          <div style={{
            marginTop: 10, padding: "10px 14px", borderRadius: 11, fontSize: 13.5, fontWeight: 600, display: "flex", alignItems: "center", gap: 8,
            background: nameMatch ? "var(--green-3)" : "color-mix(in srgb, var(--clay) 10%, transparent)",
            color: nameMatch ? "var(--green)" : "var(--clay)",
          }}>
            <Icon name={nameMatch ? "check" : "bolt"} size={15} stroke={nameMatch ? 2.4 : 1.8} />
            {nameMatch
              ? `Name matches your Aadhaar (${data.aadhaarName})`
              : `Name mismatch — Aadhaar says "${data.aadhaarName}" but UPI says "${upiResult.registered_name}". Payouts may fail.`
            }
          </div>
        )}

        {upiError && (
          <div style={{ marginTop: 12, display: "flex", alignItems: "center", gap: 8, padding: "10px 14px", borderRadius: 11, background: "color-mix(in srgb, var(--clay) 10%, transparent)", color: "var(--clay)", fontSize: 13.5, fontWeight: 600 }}>
            <Icon name="bolt" size={15} /> {upiError}
          </div>
        )}

        {data.aadhaarName && !upiResult && (
          <div style={{ marginTop: 16, padding: "12px 14px", borderRadius: 12, background: "var(--ink-3)", fontSize: 13.5, color: "var(--ink-2)" }}>
            Aadhaar name on file: <strong style={{ color: "var(--ink)" }}>{data.aadhaarName}</strong>
          </div>
        )}

        <label style={{ display: "flex", gap: 10, alignItems: "flex-start", marginTop: 18, cursor: "pointer" }}>
          <input type="checkbox" checked={data.upiNameConfirm} onChange={(e) => set("upiNameConfirm", e.target.checked)} style={{ marginTop: 3, width: 18, height: 18, accentColor: "var(--clay)", cursor: "pointer", flexShrink: 0 }} />
          <span style={{ fontSize: 14, color: "var(--ink)", lineHeight: 1.45 }}>I confirm this UPI ID is registered in the same name as my Aadhaar.</span>
        </label>
        <label style={{ display: "flex", gap: 10, alignItems: "flex-start", marginTop: 14, cursor: "pointer" }}>
          <input type="checkbox" checked={data.consent} onChange={(e) => set("consent", e.target.checked)} style={{ marginTop: 3, width: 18, height: 18, accentColor: "var(--clay)", cursor: "pointer", flexShrink: 0 }} />
          <span style={{ fontSize: 14, color: "var(--ink)", lineHeight: 1.45 }}>I consent to identity verification and agree to the <strong style={{ color: "var(--clay)" }}>Terms of Service</strong> and <strong style={{ color: "var(--clay)" }}>Privacy Policy</strong>.</span>
        </label>
      </div>
    </div>
  );
}

/* ============ STEP 5: REVIEW SUMMARY ============ */
function ReviewStep({ data, setStep }) {
  const items = [
    {
      label: "Phone", icon: "chat", step: 0,
      value: data.phoneVerified ? `+91 ${data.phone}` : "Not verified",
      status: data.phoneVerified ? "done" : "missing",
    },
    {
      label: "Aadhaar", icon: "shield", step: 1,
      value: data.aadhaarName ? `${data.aadhaarName} · ••••${data.aadhaarNumber}` : "Not provided",
      status: data.idFileName ? "done" : "missing",
      extra: data.idFileName,
    },
    {
      label: "Selfie", icon: "camera", step: 2,
      value: data.selfieFileName || "Not uploaded",
      status: data.selfieFileName ? "done" : "missing",
      preview: data.selfiePreview,
    },
    {
      label: "Liveness video", icon: "image", step: 3,
      value: data.videoFileName || "Not recorded",
      status: data.videoFileName ? "done" : "missing",
    },
    {
      label: "UPI ID", icon: "wallet", step: 4,
      value: data.upiId || "Not added",
      status: data.upiId ? "done" : "missing",
      extra: data.upiVerified ? "✓ Verified" : null,
    },
  ];

  return (
    <div>
      <StepIcon icon="check" />
      <h2 style={vStepTitle}>Review & submit</h2>
      <p style={vStepSub}>Double-check everything below before submitting. You can tap "Edit" to go back to any step.</p>

      <div style={{ marginTop: 22, display: "flex", flexDirection: "column", gap: 0 }}>
        {items.map((item, i) => (
          <div key={item.label} style={{
            display: "flex", alignItems: "center", gap: 14, padding: "16px 0",
            borderBottom: i < items.length - 1 ? "1px solid var(--line)" : "none",
          }}>
            <div style={{
              width: 42, height: 42, borderRadius: 12, flexShrink: 0, display: "grid", placeItems: "center",
              background: item.status === "done" ? "var(--green-3)" : "color-mix(in srgb, var(--clay) 8%, transparent)",
              color: item.status === "done" ? "var(--green)" : "var(--clay)",
            }}>
              {item.status === "done" ? <Icon name="check" size={20} stroke={2.4} /> : <Icon name={item.icon} size={20} />}
            </div>

            {item.preview && (
              <img src={item.preview} alt="selfie" style={{ width: 42, height: 42, borderRadius: 10, objectFit: "cover", flexShrink: 0, border: "1px solid var(--line)" }} />
            )}

            <div style={{ flex: 1, minWidth: 0 }}>
              <div style={{ fontSize: 13, fontWeight: 700, color: "var(--ink-2)", textTransform: "uppercase", letterSpacing: "0.04em" }}>{item.label}</div>
              <div style={{ fontSize: 15, fontWeight: 600, color: item.status === "done" ? "var(--ink)" : "var(--clay)", marginTop: 2, overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap" }}>
                {item.value}
              </div>
              {item.extra && (
                <div style={{ fontSize: 12.5, color: "var(--green)", fontWeight: 600, marginTop: 2 }}>{item.extra}</div>
              )}
            </div>

            <button onClick={() => setStep(item.step)} style={{
              background: "none", border: "1px solid var(--line)", borderRadius: 999, padding: "6px 14px",
              fontFamily: "var(--sans)", fontSize: 13, fontWeight: 600, color: "var(--clay)", cursor: "pointer",
            }}>Edit</button>
          </div>
        ))}
      </div>

      {/* Security assurance */}
      <div style={{
        marginTop: 22, padding: "14px 16px", borderRadius: 13, display: "flex", gap: 12, alignItems: "flex-start",
        background: "linear-gradient(135deg, color-mix(in srgb, var(--green) 6%, transparent), color-mix(in srgb, var(--blue) 4%, transparent))",
        border: "1px solid color-mix(in srgb, var(--green) 16%, transparent)",
      }}>
        <Icon name="shield" size={20} style={{ color: "var(--green)", flexShrink: 0, marginTop: 1 }} />
        <div style={{ fontSize: 13.5, color: "var(--ink-2)", lineHeight: 1.5 }}>
          <strong style={{ color: "var(--ink)" }}>End-to-end encrypted.</strong> Your documents are reviewed by our team and permanently deleted within 30 days of approval.
        </div>
      </div>
    </div>
  );
}

/* --- Shared verification components --- */

function StepIcon({ icon }) {
  return (
    <div style={{ width: 52, height: 52, borderRadius: 15, background: "color-mix(in srgb, var(--clay) 11%, transparent)", color: "var(--clay)", display: "grid", placeItems: "center", marginBottom: 18 }}>
      <Icon name={icon} size={26} />
    </div>
  );
}

function OtpInput({ value, onChange }) {
  return (
    <input value={value} onChange={(e) => onChange(e.target.value.replace(/[^\d]/g, "").slice(0, 6))} placeholder="000000" inputMode="numeric" maxLength={6}
      style={{ ...inputStyle, maxWidth: 160, letterSpacing: "0.3em", fontWeight: 700, fontSize: 20, textAlign: "center" }} />
  );
}

function VerifiedBanner({ label }) {
  return (
    <div style={{ display: "flex", alignItems: "center", gap: 10, marginTop: 18, padding: "14px 18px", borderRadius: 12, background: "var(--green-3)", color: "var(--green)", fontWeight: 700, fontSize: 15 }}>
      <Icon name="check" size={18} stroke={2.6} /> {label}
    </div>
  );
}

function UploadZone({ fileName, onUpload, label, hint, icon, preview, capture, accept = "image/*", isVideo = false }) {
  const [hover, setHover] = useV1(false);
  const pick = (e) => { const f = e.target.files[0]; if (!f) return; onUpload(f.name, f); };
  if (fileName) {
    return (
      <div style={{ display: "flex", alignItems: "center", gap: 14, padding: "12px 14px", borderRadius: 14, border: "1px solid var(--green)", background: "var(--green-3)" }}>
        {preview
          ? (isVideo
              ? <video src={preview} controls style={{ width: 96, height: 64, borderRadius: 10, objectFit: "cover", flexShrink: 0, background: "#000" }} />
              : <img src={preview} alt="upload" style={{ width: 54, height: 54, borderRadius: 10, objectFit: "cover", flexShrink: 0 }} />)
          : <span style={{ color: "var(--green)" }}><Icon name="check" size={20} stroke={2.4} /></span>}
        <div style={{ flex: 1, minWidth: 0 }}>
          <div style={{ fontWeight: 600, fontSize: 15, color: "var(--ink)", overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap" }}>{fileName}</div>
          <div style={{ fontSize: 13, color: "var(--green)", fontWeight: 600, marginTop: 2, display: "flex", alignItems: "center", gap: 5 }}>
            <Icon name="check" size={12} stroke={2.4} /> Ready to submit
          </div>
        </div>
        <button onClick={() => onUpload("", null)} style={{ background: "none", border: "none", cursor: "pointer", color: "var(--ink-2)", padding: 6 }}><Icon name="ban" size={18} /></button>
      </div>
    );
  }
  return (
    <label onMouseEnter={() => setHover(true)} onMouseLeave={() => setHover(false)} style={{
      display: "block", border: "2px dashed " + (hover ? "var(--clay)" : "var(--line-dk)"), borderRadius: 16,
      padding: "36px 24px", textAlign: "center", cursor: "pointer", transition: "border-color .2s, background .2s",
      background: hover ? "color-mix(in srgb, var(--clay) 4%, transparent)" : "transparent",
    }}>
      <div style={{ width: 48, height: 48, borderRadius: 14, background: "var(--ink-3)", color: "var(--ink-2)", display: "grid", placeItems: "center", margin: "0 auto 14px" }}>
        <Icon name={icon || "upload"} size={24} />
      </div>
      <div style={{ fontWeight: 600, fontSize: 15.5, color: "var(--ink)" }}>{label}</div>
      {hint && <div style={{ fontSize: 13.5, color: "var(--ink-2)", marginTop: 5 }}>{hint}</div>}
      <input type="file" accept={accept} {...(capture ? { capture: "user" } : {})} onChange={pick} style={{ display: "none" }} />
    </label>
  );
}

const vStepTitle = { fontFamily: "var(--display)", fontWeight: 600, fontSize: 26, letterSpacing: "-0.02em", margin: "0 0 6px", color: "var(--ink)" };
const vStepSub = { fontSize: 15.5, color: "var(--ink-2)", margin: 0, lineHeight: 1.5 };

Object.assign(window, { VerifyFlow });
