"use client";

import { useState, useRef, useEffect, useCallback } from "react";
import Link from "next/link";
import VillaLogo from "@/components/VillaLogo";
import VerificationStamp from "@/components/VerificationStamp";
import RealQRCode from "@/components/RealQRCode";
import { clientExecute, uploadFile } from "@/lib/api/client";
import { ApiError } from "@/lib/api/shared";
import type { Accommodation } from "@/lib/types";

async function dataUrlToFile(dataUrl: string, filename: string): Promise<File> {
  const res = await fetch(dataUrl);
  const blob = await res.blob();
  return new File([blob], filename, { type: blob.type || "image/jpeg" });
}

type Step = "personal" | "identity" | "selfie" | "property-auth" | "review" | "submitted";
type KYCRole = "owner" | "manager";

interface PersonalInfo {
  fullName: string; phone: string; dob: string;
  address: string; town: string; region: string;
  role: KYCRole;
  ownerName: string; ownerPhone: string; // filled when role=manager
}

interface DocSide { uploaded: boolean; fileName: string; dataUrl: string; }
interface IdentityDoc { docType: string; docNumber: string; front: DocSide; back: DocSide; }
interface SelfieData { captured: boolean; dataUrl: string; }
interface PropertyAuth {
  docType: string; // "Property title deed" | "Management authorisation letter" | ...
  fileName: string; dataUrl: string; uploaded: boolean;
  ownerOtpSent: boolean; ownerOtpVerified: boolean; ownerOtp: string;
  ownerOtpDevCode?: string; // demo mode only: the code, shown when no SMS provider is configured
}

const REGIONS = ["Greater Accra","Eastern","Ashanti","Western","Central","Volta","Northern","Upper East","Upper West","Bono","Bono East","Ahafo","Savannah","North East","Oti","Western North"];
const DOC_TYPES = ["Ghana Card (National ID)","Passport","Voter's ID","Driver's License","SSNIT Card"];

const OWNER_PROPERTY_DOCS = ["Property title deed","Utility bill in property name","Land certificate","Purchase receipt"];
const MANAGER_PROPERTY_DOCS = ["Management authorisation letter from owner","Agency agreement","Lease agreement"];

const STEPS: { id: Step; label: string }[] = [
  { id: "personal",      label: "Personal" },
  { id: "identity",      label: "Identity" },
  { id: "selfie",        label: "Selfie" },
  { id: "property-auth", label: "Property authority" },
  { id: "review",        label: "Review" },
];

function FieldLabel({ children }: { children: React.ReactNode }) {
  return <label className="block font-mono text-xs uppercase tracking-widest text-ink-soft mb-2">{children}</label>;
}
function Input(props: React.InputHTMLAttributes<HTMLInputElement>) {
  return <input className="w-full border border-mist rounded-sm px-4 py-3 text-sm bg-white text-ink focus:outline-2 focus:outline-gold focus:border-forest" {...props} />;
}
function Select({ children, ...props }: React.SelectHTMLAttributes<HTMLSelectElement> & { children: React.ReactNode }) {
  return <select className="w-full border border-mist rounded-sm px-4 py-3 text-sm bg-white text-ink focus:outline-2 focus:outline-gold focus:border-forest" {...props}>{children}</select>;
}
function Btn({ children, onClick, variant = "primary", disabled = false }: {
  children: React.ReactNode; onClick?: () => void; variant?: "primary" | "ghost"; disabled?: boolean;
}) {
  return (
    <button type="button" onClick={onClick} disabled={disabled}
      className={`inline-flex items-center justify-center gap-2 font-semibold text-sm px-6 py-3 rounded-pill transition-colors disabled:opacity-40 ${
        variant === "primary" ? "bg-forest text-white hover:bg-forest-deep" : "border border-mist text-forest hover:bg-forest hover:border-forest hover:text-white"
      }`}>
      {children}
    </button>
  );
}

function StepProgress({ current }: { current: Step }) {
  const idx = STEPS.findIndex((s) => s.id === current);
  return (
    <div className="flex items-center gap-0 mb-8">
      {STEPS.map((s, i) => {
        const done = i < idx; const active = i === idx;
        return (
          <div key={s.id} className="flex items-center flex-1 last:flex-none">
            <div className="flex flex-col items-center gap-1.5">
              <div className={`w-8 h-8 rounded-full flex items-center justify-center text-xs font-bold ${done ? "bg-forest text-white" : active ? "bg-gold text-forest-deep" : "bg-mist text-ink-soft"}`}>
                {done ? <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5" className="w-4 h-4"><path d="M5 12l5 5 9-11" strokeLinecap="round" strokeLinejoin="round" /></svg> : i + 1}
              </div>
              <span className={`text-[10px] font-mono uppercase tracking-wider whitespace-nowrap hidden sm:block ${active ? "text-gold-deep font-semibold" : done ? "text-forest" : "text-ink-soft"}`}>{s.label}</span>
            </div>
            {i < STEPS.length - 1 && <div className={`flex-1 h-0.5 mx-2 ${done ? "bg-forest" : "bg-mist"}`} />}
          </div>
        );
      })}
    </div>
  );
}

// Shared camera widget
function CameraWidget({ onCapture, onCancel, guideShape = "rect", facingModeDefault = "environment", countdown: withCountdown = false, label = "Capture photo" }: {
  onCapture: (dataUrl: string) => void; onCancel: () => void;
  guideShape?: "rect" | "oval"; facingModeDefault?: "user" | "environment";
  countdown?: boolean; label?: string;
}) {
  const videoRef  = useRef<HTMLVideoElement>(null);
  const canvasRef = useRef<HTMLCanvasElement>(null);
  const streamRef = useRef<MediaStream | null>(null);
  const [started,    setStarted]    = useState(false);
  const [camActive,  setCamActive]  = useState(false);
  const [camError,   setCamError]   = useState<string | null>(null);
  const [facingMode, setFacingMode] = useState(facingModeDefault);
  const [count,      setCount]      = useState(0);
  const [counting,   setCounting]   = useState(false);

  const stopStream = useCallback(() => {
    streamRef.current?.getTracks().forEach((t) => t.stop());
    streamRef.current = null; setCamActive(false);
  }, []);

  useEffect(() => { return () => stopStream(); }, [stopStream]);

  async function startCam(facing: "user" | "environment") {
    setCamError(null); setCamActive(false);
    try {
      streamRef.current?.getTracks().forEach((t) => t.stop());
      const stream = await navigator.mediaDevices.getUserMedia({ video: { facingMode: facing, width: { ideal: 1920 }, height: { ideal: 1080 } }, audio: false });
      streamRef.current = stream;
      if (videoRef.current) { videoRef.current.srcObject = stream; await videoRef.current.play(); }
      setCamActive(true);
    } catch (err: unknown) {
      const msg = err instanceof Error ? err.message : String(err);
      setCamError(msg.includes("Permission") || msg.includes("NotAllowed") ? "Camera access denied. Please allow access in browser settings." : "Could not start camera.");
    }
  }

  function doCapture() {
    const video = videoRef.current; const canvas = canvasRef.current;
    if (!video || !canvas) return;
    canvas.width = video.videoWidth || 1280; canvas.height = video.videoHeight || 720;
    const ctx = canvas.getContext("2d"); if (!ctx) return;
    if (facingMode === "user") { ctx.translate(canvas.width, 0); ctx.scale(-1, 1); }
    ctx.drawImage(video, 0, 0, canvas.width, canvas.height);
    stopStream(); onCapture(canvas.toDataURL("image/jpeg", 0.92));
  }

  function handleCapture() {
    if (!withCountdown) { doCapture(); return; }
    setCounting(true); setCount(3);
    let c = 3;
    const iv = setInterval(() => { c--; setCount(c); if (c <= 0) { clearInterval(iv); setCounting(false); doCapture(); } }, 1000);
  }

  return (
    <div>
      {!started && !camError && (
        <div>
          <div className="bg-ink rounded-lg overflow-hidden mb-3 flex flex-col items-center justify-center gap-3 text-white cursor-pointer hover:bg-ink/90 transition-colors" style={{ aspectRatio: guideShape === "oval" ? "4/3" : "16/10" }} onClick={() => { setStarted(true); startCam(facingMode); }}>
            <div className="w-14 h-14 rounded-full bg-white/10 flex items-center justify-center">
              <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.6" className="w-7 h-7"><path d="M23 19a2 2 0 01-2 2H3a2 2 0 01-2-2V8a2 2 0 012-2h4l2-3h6l2 3h4a2 2 0 012 2z" /><circle cx="12" cy="13" r="4" /></svg>
            </div>
            <div className="text-center"><p className="font-semibold text-sm">Tap to open camera</p></div>
          </div>
          <div className="flex gap-3">
            <button type="button" onClick={() => { setStarted(true); startCam(facingMode); }}
              className="flex-1 inline-flex items-center justify-center gap-2 font-semibold text-sm px-5 py-3 rounded-pill bg-forest text-white hover:bg-forest-deep transition-colors">
              <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" className="w-4 h-4"><path d="M23 19a2 2 0 01-2 2H3a2 2 0 01-2-2V8a2 2 0 012-2h4l2-3h6l2 3h4a2 2 0 012 2z" /><circle cx="12" cy="13" r="4" /></svg>
              Open camera
            </button>
            <button type="button" onClick={onCancel} className="inline-flex items-center justify-center font-semibold text-sm px-4 py-3 rounded-pill border border-mist text-ink-soft hover:text-clay transition-colors">Cancel</button>
          </div>
        </div>
      )}
      {camError && (
        <div className="bg-[#F5EAE6] border border-clay rounded-md p-5 text-center">
          <p className="text-sm text-clay mb-3">{camError}</p>
          <div className="flex gap-3 justify-center">
            <button type="button" onClick={() => startCam(facingMode)} className="text-sm font-semibold text-forest hover:underline">Try again</button>
            <button type="button" onClick={onCancel} className="text-sm text-ink-soft hover:underline">Go back</button>
          </div>
        </div>
      )}
      {started && !camError && (
        <div>
          <div className="bg-ink rounded-lg overflow-hidden mb-3 relative" style={{ aspectRatio: guideShape === "oval" ? "4/3" : "16/10" }}>
            <video ref={videoRef} className="w-full h-full object-cover" style={{ transform: facingMode === "user" ? "scaleX(-1)" : "none" }} playsInline muted />
            {camActive && !counting && (
              <div className="absolute inset-0 flex items-center justify-center pointer-events-none">
                {guideShape === "oval"
                  ? <div className="border-2 border-white/50 border-dashed rounded-full" style={{ width: "42%", height: "58%", marginTop: "-8%" }} />
                  : <div className="relative border-2 border-white/60 border-dashed rounded-lg" style={{ width: "82%", height: "62%" }}><span className="absolute -top-6 left-0 right-0 flex justify-center"><span className="text-white text-xs bg-black/50 px-3 py-0.5 rounded-pill">Position within frame</span></span></div>
                }
              </div>
            )}
            {counting && <div className="absolute inset-0 flex items-center justify-center bg-black/30"><div className="w-24 h-24 rounded-full bg-black/60 flex items-center justify-center"><span className="text-white font-display font-bold text-5xl">{count}</span></div></div>}
            {!camActive && !camError && <div className="absolute inset-0 flex items-center justify-center"><div className="w-8 h-8 border-2 border-white border-t-transparent rounded-full animate-spin" /></div>}
            {camActive && (
              <button onClick={() => { const next = facingMode === "user" ? "environment" : "user"; setFacingMode(next); startCam(next); }}
                className="absolute top-2 right-2 w-9 h-9 rounded-full bg-black/40 hover:bg-black/60 flex items-center justify-center transition-colors">
                <svg viewBox="0 0 24 24" fill="none" stroke="white" strokeWidth="2" className="w-4 h-4"><path d="M1 4v6h6M23 20v-6h-6" strokeLinecap="round" strokeLinejoin="round" /><path d="M20.49 9A9 9 0 005.64 5.64L1 10M23 14l-4.64 4.36A9 9 0 013.51 15" strokeLinecap="round" strokeLinejoin="round" /></svg>
              </button>
            )}
            <canvas ref={canvasRef} className="hidden" />
          </div>
          <div className="flex gap-3">
            <button type="button" onClick={handleCapture} disabled={!camActive || counting}
              className="flex-1 inline-flex items-center justify-center gap-2 font-semibold text-sm px-5 py-3 rounded-pill bg-forest text-white hover:bg-forest-deep transition-colors disabled:opacity-40">
              <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" className="w-4 h-4"><path d="M23 19a2 2 0 01-2 2H3a2 2 0 01-2-2V8a2 2 0 012-2h4l2-3h6l2 3h4a2 2 0 012 2z" /><circle cx="12" cy="13" r="4" /></svg>
              {withCountdown && !counting ? `${label} (3s countdown)` : label}
            </button>
            <button type="button" onClick={() => { stopStream(); onCancel(); }} className="inline-flex items-center justify-center font-semibold text-sm px-4 py-3 rounded-pill border border-mist text-ink-soft hover:text-clay transition-colors">Cancel</button>
          </div>
        </div>
      )}
    </div>
  );
}

// Doc side capture widget (camera / upload / QR)
function DocSideWidget({ side, data, onChange }: { side: "front" | "back"; data: DocSide; onChange: (d: DocSide) => void }) {
  const fileRef = useRef<HTMLInputElement>(null);
  const [mode, setMode] = useState<"choose" | "camera" | "upload-loading">("choose");
  const qrUrl = typeof window !== "undefined" ? `${window.location.origin}/stay/kyc?mobile=id-${side}` : "https://villa.app/stay/kyc";

  function handleCapture(dataUrl: string) { onChange({ uploaded: true, fileName: `Camera — ${side}`, dataUrl }); setMode("choose"); }
  function handleFile(e: React.ChangeEvent<HTMLInputElement>) {
    const file = e.target.files?.[0]; if (!file) { setMode("choose"); return; }
    const reader = new FileReader();
    reader.onload = (ev) => onChange({ uploaded: true, fileName: file.name, dataUrl: ev.target?.result as string });
    reader.readAsDataURL(file); setMode("choose");
  }
  function clear() { onChange({ uploaded: false, fileName: "", dataUrl: "" }); setMode("choose"); if (fileRef.current) fileRef.current.value = ""; }

  return (
    <div className="bg-white border border-mist rounded-md overflow-hidden">
      <div className="flex items-center justify-between px-4 py-3 border-b border-mist bg-sage/40">
        <div className="flex items-center gap-2">
          <span className={`w-6 h-6 rounded-full flex items-center justify-center text-xs font-bold ${data.uploaded ? "bg-forest text-white" : "bg-mist text-ink-soft"}`}>
            {data.uploaded ? <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5" className="w-3 h-3"><path d="M5 12l5 5 9-11" strokeLinecap="round" strokeLinejoin="round" /></svg> : side === "front" ? "F" : "B"}
          </span>
          <span className="font-semibold text-sm text-forest-deep">{side === "front" ? "Front of ID" : "Back of ID"}</span>
        </div>
        {data.uploaded && <button type="button" onClick={clear} className="text-xs text-ink-soft hover:text-clay transition-colors">Retake / replace</button>}
      </div>
      <div className="p-4">
        {data.uploaded && data.dataUrl ? (
          // eslint-disable-next-line @next/next/no-img-element
          <img src={data.dataUrl} alt={side} className="w-full object-contain rounded-sm" style={{ maxHeight: 200, background: "#F4F6F0" }} />
        ) : mode === "choose" ? (
          <div className="grid grid-cols-3 gap-2">
            {[
              { id: "camera", icon: <svg viewBox="0 0 24 24" fill="none" stroke="#1E4A3D" strokeWidth="1.8" className="w-6 h-6"><path d="M23 19a2 2 0 01-2 2H3a2 2 0 01-2-2V8a2 2 0 012-2h4l2-3h6l2 3h4a2 2 0 012 2z" /><circle cx="12" cy="13" r="4" /></svg>, label: "Camera" },
              { id: "upload", icon: <svg viewBox="0 0 24 24" fill="none" stroke="#1E4A3D" strokeWidth="1.8" className="w-6 h-6"><path d="M21 15v4a2 2 0 01-2 2H5a2 2 0 01-2-2v-4M17 8l-5-5-5 5M12 3v12" strokeLinecap="round" strokeLinejoin="round" /></svg>, label: "Upload" },
              { id: "qr", icon: <svg viewBox="0 0 24 24" fill="none" stroke="#1E4A3D" strokeWidth="1.8" className="w-6 h-6"><rect x="3" y="3" width="7" height="7" rx="1" /><rect x="14" y="3" width="7" height="7" rx="1" /><rect x="3" y="14" width="7" height="7" rx="1" /><path d="M14 14h1v1h-1zM17 14h1v1h-1zM20 14h1v1h-1zM14 17h1v1h-1zM17 17h1v1h-1zM20 17h1v1h-1zM14 20h1v1h-1zM17 20h1v1h-1zM20 20h1v1h-1z" fill="#1E4A3D" /></svg>, label: "Scan QR" },
            ].map(({ id, icon, label }) => (
              <button key={id} type="button"
                onClick={() => {
                  if (id === "upload") { setMode("upload-loading"); setTimeout(() => fileRef.current?.click(), 50); }
                  else if (id === "camera") setMode("camera");
                  else setMode("qr" as typeof mode);
                }}
                className="flex flex-col items-center gap-2 py-4 px-2 border-2 border-dashed border-mist rounded-md hover:border-forest hover:bg-sage/40 transition-colors">
                <div className="w-10 h-10 rounded-full bg-sage flex items-center justify-center">{icon}</div>
                <span className="text-xs font-semibold text-forest-deep">{label}</span>
              </button>
            ))}
            <input ref={fileRef} type="file" accept="image/*,.pdf" className="hidden" onChange={handleFile} />
          </div>
        ) : mode === "camera" ? (
          <CameraWidget onCapture={handleCapture} onCancel={() => setMode("choose")} guideShape="rect" facingModeDefault="environment" />
        ) : (mode as string) === "qr" ? (
          <div>
            <p className="text-sm text-ink-soft mb-3 text-center">Scan with your phone camera to open this step on your phone.</p>
            <div className="flex justify-center mb-3">
              <div className="border-4 border-forest rounded-xl p-3 bg-white shadow-card inline-block">
                <RealQRCode url={qrUrl} size={200} />
              </div>
            </div>
            <p className="text-xs text-ink-soft text-center mb-2">Open phone camera → point at code → tap the link.</p>
            <button type="button" onClick={() => setMode("choose")} className="text-sm text-ink-soft hover:text-clay underline block mx-auto">← Go back</button>
          </div>
        ) : (
          <div className="flex flex-col items-center justify-center gap-3 py-8">
            <div className="w-8 h-8 border-2 border-forest border-t-transparent rounded-full animate-spin" />
            <span className="text-sm text-ink-soft">Opening file picker…</span>
            <button type="button" onClick={() => setMode("choose")} className="text-xs text-ink-soft hover:text-clay underline">Cancel</button>
            <input ref={fileRef} type="file" accept="image/*,.pdf" className="hidden" onChange={handleFile} />
          </div>
        )}
      </div>
    </div>
  );
}

export default function StayKYCPage() {
  const [step, setStep] = useState<Step>("personal");
  const [personal, setPersonal] = useState<PersonalInfo>({
    fullName: "", phone: "", dob: "", address: "", town: "Akim Oda", region: "Eastern",
    role: "owner", ownerName: "", ownerPhone: "",
  });
  const [identity, setIdentity] = useState<IdentityDoc>({
    docType: "", docNumber: "", front: { uploaded: false, fileName: "", dataUrl: "" }, back: { uploaded: false, fileName: "", dataUrl: "" },
  });
  const [selfie,  setSelfie]  = useState<SelfieData>({ captured: false, dataUrl: "" });
  const [selfieMode,  setSelfieMode]  = useState<"choose" | "camera" | "qr-show">("choose");
  const [selfiePreview, setSelfiePreview] = useState<string | null>(null);
  const [propertyAuth, setPropertyAuth] = useState<PropertyAuth>({
    docType: "", fileName: "", dataUrl: "", uploaded: false,
    ownerOtpSent: false, ownerOtpVerified: false, ownerOtp: "",
  });
  const [agreed, setAgreed] = useState(false);

  const qrSelfieUrl = typeof window !== "undefined" ? `${window.location.origin}/stay/kyc?mobile=selfie` : "https://villa.app/stay/kyc";
  const needsBack = identity.docType !== "Passport";
  const identityValid = identity.docType && identity.docNumber && identity.front.uploaded && (!needsBack || identity.back.uploaded);
  const propertyAuthValid = propertyAuth.uploaded && (personal.role === "owner" || propertyAuth.ownerOtpVerified);

  function handleSelfieCapture(dataUrl: string) {
    setSelfiePreview(dataUrl);
    setSelfie({ captured: true, dataUrl });
    setSelfieMode("choose");
  }

  const authFileRef = useRef<HTMLInputElement>(null);
  function handleAuthFile(e: React.ChangeEvent<HTMLInputElement>) {
    const file = e.target.files?.[0]; if (!file) return;
    const reader = new FileReader();
    reader.onload = (ev) => setPropertyAuth((p) => ({ ...p, uploaded: true, fileName: file.name, dataUrl: ev.target?.result as string }));
    reader.readAsDataURL(file);
  }

  const [propertyId, setPropertyId] = useState<string>("");
  const [submitting, setSubmitting] = useState(false);
  const [submitError, setSubmitError] = useState<string | null>(null);

  // The property to verify is the accommodation this owner just registered.
  useEffect(() => {
    clientExecute<Accommodation>("accommodation.find-by-owner")
      .then((a) => setPropertyId(a?.id ?? ""))
      .catch(() => { /* ignore */ });
  }, []);

  async function sendOwnerOtp() {
    setSubmitError(null);
    try {
      const res = await clientExecute<{ sent: boolean; devCode?: string }>("stay-kyc.send-owner-otp", { ownerPhone: personal.ownerPhone });
      setPropertyAuth((p) => ({ ...p, ownerOtpSent: true, ownerOtpDevCode: res.devCode }));
    } catch (e) { setSubmitError(e instanceof ApiError ? e.message : "Couldn't send code."); }
  }
  async function verifyOwnerOtp() {
    setSubmitError(null);
    try {
      const res = await clientExecute<{ verified: boolean }>("stay-kyc.verify-owner-otp", { ownerPhone: personal.ownerPhone, code: propertyAuth.ownerOtp });
      if (res.verified) setPropertyAuth((p) => ({ ...p, ownerOtpVerified: true }));
      else setSubmitError("That code is incorrect or has expired.");
    } catch (e) { setSubmitError(e instanceof ApiError ? e.message : "Couldn't verify code."); }
  }

  async function submitStayKyc() {
    setSubmitting(true);
    setSubmitError(null);
    try {
      const isManager = personal.role === "manager";
      const front = await uploadFile(await dataUrlToFile(identity.front.dataUrl, "id-front.jpg"));
      const back = needsBack && identity.back.dataUrl ? await uploadFile(await dataUrlToFile(identity.back.dataUrl, "id-back.jpg")) : null;
      const selfieUp = await uploadFile(await dataUrlToFile(selfie.dataUrl, "selfie.jpg"));
      const propDoc = await uploadFile(await dataUrlToFile(propertyAuth.dataUrl, propertyAuth.fileName || "property-doc"));
      await clientExecute("stay-kyc.submit", {
        role: personal.role, fullName: personal.fullName, phone: personal.phone, dob: personal.dob,
        address: personal.address, town: personal.town, region: personal.region, propertyId,
        docType: identity.docType, docNumber: identity.docNumber,
        frontFile: front.url, backFile: back?.url, selfieFile: selfieUp.url,
        propertyDocType: propertyAuth.docType, propertyDocFile: propDoc.url,
        realOwnerName: isManager ? personal.ownerName : undefined,
        realOwnerPhone: isManager ? personal.ownerPhone : undefined,
        ownerOtpVerified: isManager ? propertyAuth.ownerOtpVerified : undefined,
        agreed: true,
      });
      setStep("submitted");
    } catch (e) {
      setSubmitError(e instanceof ApiError ? e.message : "Submission failed. Please try again.");
    } finally {
      setSubmitting(false);
    }
  }

  if (step === "submitted") {
    return (
      <div className="max-w-2xl mx-auto px-6 py-12 text-center">
        <VerificationStamp variant="pending" size={96} className="mx-auto mb-6" />
        <div className="font-mono text-xs uppercase tracking-widest text-gold-deep mb-2">Application submitted</div>
        <h2 className="font-display font-semibold text-2xl text-forest-deep mb-3">KYC verification submitted</h2>
        <p className="text-ink-soft max-w-[44ch] mx-auto mb-8">
          Villa will review your identity documents and property authority within <strong>1–2 business days</strong>. Once approved, your property will go live on Villa Stay.
        </p>
        <div className="bg-white border border-mist rounded-md p-5 max-w-sm mx-auto mb-8 text-left">
          <div className="font-mono text-xs uppercase tracking-widest text-ink-soft mb-3">What happens next</div>
          {[
            { n: "1", label: "Identity review", desc: "Villa verifies your government-issued ID and selfie" },
            { n: "2", label: "Property authority check", desc: personal.role === "manager" ? "Management letter and owner phone verification confirmed" : "Property title or ownership document checked" },
            { n: "3", label: "Property goes live", desc: "Your accommodation appears on Villa Stay for guests to book" },
          ].map(({ n, label, desc }) => (
            <div key={n} className="flex gap-3 py-3 border-b border-mist last:border-b-0">
              <div className="w-6 h-6 rounded-full bg-mist flex items-center justify-center text-xs font-bold text-forest-deep shrink-0">{n}</div>
              <div><div className="text-sm font-semibold text-ink">{label}</div><div className="text-xs text-ink-soft">{desc}</div></div>
            </div>
          ))}
        </div>
        <div className="flex flex-col sm:flex-row gap-3 justify-center">
          <Link href="/accommodation/dashboard" className="inline-flex items-center justify-center font-semibold text-sm px-6 py-3 rounded-pill bg-forest text-white hover:bg-forest-deep transition-colors">
            Go to my dashboard
          </Link>
          <Link href="/stay" className="inline-flex items-center justify-center font-semibold text-sm px-6 py-3 rounded-pill border border-mist text-forest hover:bg-forest hover:border-forest hover:text-white transition-colors">
            Browse Villa Stay
          </Link>
        </div>
      </div>
    );
  }

  return (
    <div className="max-w-2xl mx-auto px-6 py-12">
      <div className="mb-8">
        <Link href="/"><VillaLogo size="sm" className="mb-6" /></Link>
        <div className="font-mono text-xs uppercase tracking-widest text-gold-deep mb-2">Villa Stay · Identity verification</div>
        <h1 className="font-display font-semibold text-3xl text-forest-deep mb-1">Complete your KYC</h1>
        <p className="text-ink-soft text-sm">All accommodation owners and managers on Villa Stay must complete identity verification before their property goes live. This protects guests and builds trust on the platform.</p>
      </div>

      <StepProgress current={step} />
      {submitError && <p className="max-w-2xl mx-auto text-center text-sm text-red-600 mt-3">{submitError}</p>}

      <div className="bg-white border border-mist rounded-lg p-6 sm:p-8 shadow-card">

        {/* Step 1 — Personal */}
        {step === "personal" && (
          <div>
            <h2 className="font-display font-semibold text-2xl text-forest-deep mb-1">Personal details</h2>
            <p className="text-sm text-ink-soft mb-6">Your personal information is used to verify your identity and is not shared publicly.</p>
            <div className="grid grid-cols-1 sm:grid-cols-2 gap-5">
              <div className="sm:col-span-2">
                <FieldLabel>My role</FieldLabel>
                <div className="grid grid-cols-2 gap-3">
                  {(["owner", "manager"] as const).map((r) => (
                    <button key={r} type="button" onClick={() => setPersonal((p) => ({ ...p, role: r }))}
                      className={`text-left border rounded-md p-3 text-sm transition-colors ${personal.role === r ? "border-forest bg-[#E8F2EC]" : "border-mist bg-white hover:border-forest"}`}>
                      <div className="font-semibold text-forest-deep capitalize">{r}</div>
                      <div className="text-xs text-ink-soft mt-0.5">{r === "owner" ? "I own this property" : "I manage it on behalf of the owner"}</div>
                    </button>
                  ))}
                </div>
              </div>
              <div className="sm:col-span-2"><FieldLabel>Full legal name</FieldLabel><Input value={personal.fullName} onChange={(e) => setPersonal((p) => ({ ...p, fullName: e.target.value }))} placeholder="As on your ID" /></div>
              <div><FieldLabel>Phone number</FieldLabel><Input type="tel" value={personal.phone} onChange={(e) => setPersonal((p) => ({ ...p, phone: e.target.value }))} placeholder="024 000 0000" /></div>
              <div><FieldLabel>Date of birth</FieldLabel><Input type="date" value={personal.dob} onChange={(e) => setPersonal((p) => ({ ...p, dob: e.target.value }))} /></div>
              <div className="sm:col-span-2"><FieldLabel>Residential address</FieldLabel><Input value={personal.address} onChange={(e) => setPersonal((p) => ({ ...p, address: e.target.value }))} placeholder="Street or area" /></div>
              <div><FieldLabel>Town</FieldLabel><Input value={personal.town} onChange={(e) => setPersonal((p) => ({ ...p, town: e.target.value }))} placeholder="e.g. Akim Oda" /></div>
              <div><FieldLabel>Region</FieldLabel><Select value={personal.region} onChange={(e) => setPersonal((p) => ({ ...p, region: e.target.value }))}><option value="">Select</option>{REGIONS.map((r) => <option key={r}>{r}</option>)}</Select></div>

              {/* Manager succession fields */}
              {personal.role === "manager" && (
                <>
                  <div className="sm:col-span-2">
                    <div className="bg-[#FBF1E1] border border-gold rounded-sm px-4 py-3 text-xs text-gold-deep mb-4">
                      <strong>Manager succession protection:</strong> Villa requires the property owner&apos;s details on record. If you as manager are no longer available, the owner can use these details to reclaim and transfer the property listing to a new manager.
                    </div>
                  </div>
                  <div><FieldLabel>Property owner&apos;s name</FieldLabel><Input value={personal.ownerName} onChange={(e) => setPersonal((p) => ({ ...p, ownerName: e.target.value }))} placeholder="Owner's full name" /></div>
                  <div><FieldLabel>Owner&apos;s phone number</FieldLabel><Input type="tel" value={personal.ownerPhone} onChange={(e) => setPersonal((p) => ({ ...p, ownerPhone: e.target.value }))} placeholder="024 000 0000" /></div>
                </>
              )}
            </div>
            <div className="mt-8 flex justify-end">
              <Btn onClick={() => setStep("identity")} disabled={!personal.fullName || !personal.phone || !personal.dob || (personal.role === "manager" && (!personal.ownerName || !personal.ownerPhone))}>
                Continue →
              </Btn>
            </div>
          </div>
        )}

        {/* Step 2 — Identity document */}
        {step === "identity" && (
          <div>
            <h2 className="font-display font-semibold text-2xl text-forest-deep mb-1">Identity document</h2>
            <p className="text-sm text-ink-soft mb-6">Upload clear photos of your government-issued ID. Use camera, upload, or QR code to capture on your phone.</p>
            <div className="flex flex-col gap-5">
              <div><FieldLabel>Document type</FieldLabel>
                <Select value={identity.docType} onChange={(e) => setIdentity((d) => ({ ...d, docType: e.target.value }))}>
                  <option value="">Select document type</option>
                  {DOC_TYPES.map((d) => <option key={d}>{d}</option>)}
                </Select>
              </div>
              <div><FieldLabel>Document number</FieldLabel>
                <Input value={identity.docNumber} onChange={(e) => setIdentity((d) => ({ ...d, docNumber: e.target.value }))}
                  placeholder={identity.docType === "Ghana Card (National ID)" ? "GHA-000000000-0" : "Document number"} />
              </div>
              <DocSideWidget side="front" data={identity.front} onChange={(front) => setIdentity((d) => ({ ...d, front }))} />
              {needsBack && <DocSideWidget side="back" data={identity.back} onChange={(back) => setIdentity((d) => ({ ...d, back }))} />}
              <div className="bg-[#FBF1E1] border border-gold rounded-sm px-4 py-3 text-sm text-gold-deep">
                Photos must be clear, unexpired, and show your full name, photo, and ID number. Blurry or edited documents will be rejected.
              </div>
            </div>
            <div className="mt-8 flex justify-between">
              <Btn variant="ghost" onClick={() => setStep("personal")}>← Back</Btn>
              <Btn onClick={() => setStep("selfie")} disabled={!identityValid}>Continue →</Btn>
            </div>
          </div>
        )}

        {/* Step 3 — Selfie */}
        {step === "selfie" && (
          <div>
            <h2 className="font-display font-semibold text-2xl text-forest-deep mb-1">Selfie verification</h2>
            <p className="text-sm text-ink-soft mb-5">Take a live photo of yourself holding your ID next to your face.</p>
            <div className="grid grid-cols-2 sm:grid-cols-4 gap-2 mb-5">
              {[
                { label: "Face visible",   icon: <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" className="w-6 h-6"><circle cx="12" cy="8" r="4"/><path d="M4 20c0-4 3.6-7 8-7s8 3 8 7" strokeLinecap="round"/></svg> },
                { label: "ID next to face",icon: <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" className="w-6 h-6"><rect x="2" y="5" width="20" height="14" rx="2"/><circle cx="8" cy="12" r="2"/><path d="M14 9h4M14 12h4" strokeLinecap="round"/></svg> },
                { label: "Good lighting",  icon: <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" className="w-6 h-6"><circle cx="12" cy="12" r="4"/><path d="M12 2v2M12 20v2M4.22 4.22l1.42 1.42M18.36 18.36l1.42 1.42M2 12h2M20 12h2M4.22 19.78l1.42-1.42M18.36 5.64l1.42-1.42" strokeLinecap="round"/></svg> },
                { label: "ID readable",    icon: <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" className="w-6 h-6"><circle cx="11" cy="11" r="7"/><path d="M21 21l-4.35-4.35" strokeLinecap="round"/></svg> },
              ].map(({ icon, label }) => (
                <div key={label} className="flex flex-col items-center text-center gap-1.5 bg-white border border-mist rounded-sm p-3">
                  <span className="text-forest">{icon}</span>
                  <span className="text-xs text-ink-soft">{label}</span>
                </div>
              ))}
            </div>

            {selfie.captured && selfiePreview ? (
              <div className="bg-ink rounded-xl overflow-hidden mb-4 relative">
                {/* eslint-disable-next-line @next/next/no-img-element */}
                <img src={selfiePreview} alt="Selfie" className="w-full object-cover" style={{ maxHeight: 380 }} />
                <div className="absolute top-3 left-3 flex items-center gap-2 bg-forest/90 text-white text-xs font-mono uppercase tracking-wider px-3 py-1.5 rounded-pill">
                  <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5" className="w-3.5 h-3.5"><path d="M5 12l5 5 9-11" strokeLinecap="round" strokeLinejoin="round" /></svg>
                  Selfie captured
                </div>
              </div>
            ) : selfieMode === "choose" ? (
              <div className="grid grid-cols-1 sm:grid-cols-2 gap-3 mb-5">
                {[
                  { id: "camera", icon: <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" className="w-7 h-7"><path d="M23 19a2 2 0 01-2 2H3a2 2 0 01-2-2V8a2 2 0 012-2h4l2-3h6l2 3h4a2 2 0 012 2z"/><circle cx="12" cy="13" r="4"/></svg>, label: "Use this device", sub: "Webcam or laptop camera" },
                  { id: "qr-show", icon: <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" className="w-7 h-7"><rect x="5" y="2" width="14" height="20" rx="2"/><path d="M12 18h.01" strokeLinecap="round"/><path d="M9 7h6M9 11h4" strokeLinecap="round"/></svg>, label: "Use mobile phone", sub: "Scan QR to open on phone" },
                ].map(({ id, icon, label, sub }) => (
                  <button key={id} type="button" onClick={() => setSelfieMode(id as typeof selfieMode)}
                    className="flex flex-col items-center gap-3 p-5 border-2 border-dashed border-mist rounded-md hover:border-forest hover:bg-sage/40 transition-colors">
                    <span className="text-3xl">{icon}</span>
                    <div className="text-center"><div className="font-semibold text-sm text-forest-deep">{label}</div><div className="text-xs text-ink-soft mt-0.5">{sub}</div></div>
                  </button>
                ))}
              </div>
            ) : selfieMode === "camera" ? (
              <div className="mb-5">
                <CameraWidget onCapture={handleSelfieCapture} onCancel={() => setSelfieMode("choose")} guideShape="oval" facingModeDefault="user" countdown label="Take selfie" />
              </div>
            ) : (
              <div className="mb-5">
                <p className="text-sm text-ink-soft mb-4 text-center">Open your phone camera app and point it at this code.</p>
                <div className="flex justify-center mb-3">
                  <div className="border-4 border-forest rounded-xl p-4 bg-white shadow-card inline-block">
                    <RealQRCode url={qrSelfieUrl} size={240} />
                  </div>
                </div>
                <button type="button" onClick={() => setSelfieMode("choose")} className="text-sm text-ink-soft hover:text-clay underline block mx-auto">← Go back</button>
              </div>
            )}

            {selfie.captured && (
              <div className="flex justify-center mb-5">
                <button type="button" onClick={() => { setSelfiePreview(null); setSelfie({ captured: false, dataUrl: "" }); setSelfieMode("choose"); }}
                  className="inline-flex items-center gap-2 font-semibold text-sm px-6 py-3 rounded-pill border border-mist text-forest hover:bg-forest hover:border-forest hover:text-white transition-colors">
                  Retake selfie
                </button>
              </div>
            )}

            <div className="mt-8 flex justify-between">
              <Btn variant="ghost" onClick={() => setStep("identity")}>← Back</Btn>
              <Btn onClick={() => setStep("property-auth")} disabled={!selfie.captured}>Continue →</Btn>
            </div>
          </div>
        )}

        {/* Step 4 — Property authority */}
        {step === "property-auth" && (
          <div>
            <h2 className="font-display font-semibold text-2xl text-forest-deep mb-1">Property authority</h2>
            <p className="text-sm text-ink-soft mb-6">
              {personal.role === "owner"
                ? "Provide proof that you own or have the right to list this property on Villa Stay."
                : "Provide a signed authorisation letter from the property owner, and verify the owner's phone number."}
            </p>

            <div className="flex flex-col gap-5">
              <div>
                <FieldLabel>Document type</FieldLabel>
                <Select value={propertyAuth.docType} onChange={(e) => setPropertyAuth((p) => ({ ...p, docType: e.target.value }))}>
                  <option value="">Select document type</option>
                  {(personal.role === "owner" ? OWNER_PROPERTY_DOCS : MANAGER_PROPERTY_DOCS).map((d) => <option key={d}>{d}</option>)}
                </Select>
              </div>

              {/* Upload */}
              <div>
                <FieldLabel>Upload document</FieldLabel>
                <input ref={authFileRef} type="file" accept="image/*,.pdf" className="hidden" onChange={handleAuthFile} />
                {propertyAuth.uploaded ? (
                  <div className="border border-forest bg-[#E8F2EC] rounded-md overflow-hidden">
                    {propertyAuth.dataUrl && propertyAuth.dataUrl.startsWith("data:image") && (
                      // eslint-disable-next-line @next/next/no-img-element
                      <img src={propertyAuth.dataUrl} alt="Authority doc" className="w-full object-contain" style={{ maxHeight: 200, background: "#F4F6F0" }} />
                    )}
                    <div className="flex items-center justify-between px-4 py-3">
                      <div className="flex items-center gap-2">
                        <svg viewBox="0 0 24 24" fill="none" stroke="#1E4A3D" strokeWidth="2" className="w-4 h-4 shrink-0"><path d="M5 12l5 5 9-11" strokeLinecap="round" strokeLinejoin="round" /></svg>
                        <span className="text-sm font-semibold text-forest-deep">{propertyAuth.fileName}</span>
                      </div>
                      <button type="button" onClick={() => setPropertyAuth((p) => ({ ...p, uploaded: false, fileName: "", dataUrl: "" }))} className="text-xs text-ink-soft hover:text-clay">Replace</button>
                    </div>
                  </div>
                ) : (
                  <button type="button" onClick={() => authFileRef.current?.click()}
                    className="w-full border-2 border-dashed border-mist rounded-md p-8 text-center hover:border-forest transition-colors">
                    <svg viewBox="0 0 24 24" fill="none" stroke="#5B6B63" strokeWidth="1.6" className="w-10 h-10 mx-auto mb-3"><path d="M21 15v4a2 2 0 01-2 2H5a2 2 0 01-2-2v-4M17 8l-5-5-5 5M12 3v12" strokeLinecap="round" strokeLinejoin="round" /></svg>
                    <p className="text-sm text-ink-soft"><strong className="text-forest">Click to upload</strong> or drag document here</p>
                    <p className="text-xs text-ink-soft mt-1">JPG, PNG, or PDF — max 10MB</p>
                  </button>
                )}
              </div>

              {/* Manager only: verify owner phone via OTP */}
              {personal.role === "manager" && (
                <div className="bg-white border border-mist rounded-md p-5">
                  <div className="font-semibold text-sm text-forest-deep mb-2">Verify property owner&apos;s phone number</div>
                  <p className="text-xs text-ink-soft mb-4">
                    We will send a one-time code to the owner&apos;s phone number (<strong>{personal.ownerPhone}</strong>) to confirm they have authorised this listing. This protects the owner if the management arrangement changes.
                  </p>
                  {!propertyAuth.ownerOtpSent ? (
                    <button type="button" onClick={sendOwnerOtp}
                      className="inline-flex items-center gap-2 font-semibold text-sm px-5 py-2.5 rounded-pill bg-forest text-white hover:bg-forest-deep transition-colors">
                      Send verification code to owner
                    </button>
                  ) : !propertyAuth.ownerOtpVerified ? (
                    <div className="flex flex-col gap-3">
                      {propertyAuth.ownerOtpDevCode && (
                        <div className="flex items-center gap-2 text-xs bg-gold/10 border border-gold/40 text-gold-deep rounded-md px-3 py-2">
                          <span className="font-mono uppercase tracking-widest text-[10px]">Demo</span>
                          SMS isn&apos;t configured yet — your code is{" "}
                          <strong className="font-mono text-sm tracking-wider text-forest-deep">{propertyAuth.ownerOtpDevCode}</strong>
                        </div>
                      )}
                      <div className="flex gap-3">
                        <Input value={propertyAuth.ownerOtp} onChange={(e) => setPropertyAuth((p) => ({ ...p, ownerOtp: e.target.value }))}
                          placeholder="Enter 4-digit code" className="max-w-[160px]" maxLength={6} />
                        <button type="button" onClick={verifyOwnerOtp}
                          className="inline-flex items-center font-semibold text-sm px-5 py-2.5 rounded-pill bg-forest text-white hover:bg-forest-deep transition-colors">
                          Verify
                        </button>
                        <button type="button" onClick={sendOwnerOtp} className="text-xs text-ink-soft hover:underline self-center">Resend</button>
                      </div>
                    </div>
                  ) : (
                    <div className="flex items-center gap-2 text-forest text-sm font-semibold">
                      <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" className="w-5 h-5"><path d="M5 12l5 5 9-11" strokeLinecap="round" strokeLinejoin="round" /></svg>
                      Owner&apos;s phone verified
                    </div>
                  )}
                </div>
              )}

              {/* Manager succession notice */}
              {personal.role === "manager" && (
                <div className="bg-[#E8F2EC] border border-forest/20 rounded-sm px-4 py-3 text-xs text-forest-deep">
                  <strong>Manager succession protection:</strong> If you leave this role, the property owner (<strong>{personal.ownerName}</strong>) can contact Villa at any time to transfer this listing to a new manager. Villa will verify the owner&apos;s identity using the details provided and the phone verification above.
                </div>
              )}
            </div>

            <div className="mt-8 flex justify-between">
              <Btn variant="ghost" onClick={() => setStep("selfie")}>← Back</Btn>
              <Btn onClick={() => setStep("review")} disabled={!propertyAuthValid || !propertyAuth.docType}>Review & submit →</Btn>
            </div>
          </div>
        )}

        {/* Step 5 — Review */}
        {step === "review" && (
          <div>
            <h2 className="font-display font-semibold text-2xl text-forest-deep mb-1">Review & submit</h2>
            <p className="text-sm text-ink-soft mb-6">Check everything carefully before submitting.</p>
            <div className="flex flex-col gap-4 mb-6">
              <div className="bg-sage border border-mist rounded-md p-5">
                <div className="font-mono text-xs uppercase tracking-widest text-gold-deep mb-3">Personal details</div>
                {[["Role", personal.role],["Full name", personal.fullName],["Phone", personal.phone],["Date of birth", personal.dob],["Town", personal.town],["Region", personal.region],...(personal.role === "manager" ? [["Owner's name", personal.ownerName],["Owner's phone", personal.ownerPhone]] : [])].map(([l, v]) => (
                  <div key={l as string} className="flex justify-between py-2 border-b border-mist last:border-b-0 text-sm">
                    <span className="text-ink-soft">{l}</span><span className="font-medium">{v}</span>
                  </div>
                ))}
              </div>
              <div className="bg-sage border border-mist rounded-md p-5">
                <div className="font-mono text-xs uppercase tracking-widest text-gold-deep mb-3">Identity document</div>
                {[["Type", identity.docType], ["Number", identity.docNumber]].map(([l, v]) => (
                  <div key={l as string} className="flex justify-between py-2 border-b border-mist text-sm">
                    <span className="text-ink-soft">{l}</span><span className="font-medium">{v}</span>
                  </div>
                ))}
                <div className="flex gap-3 mt-4">
                  {([
                    { label: "Front of ID", side: identity.front },
                    { label: "Back of ID",  side: identity.back },
                  ] as { label: string; side: typeof identity.front }[]).map(({ label, side }) => (
                    <div key={label} className="flex-1">
                      <div className="font-mono text-[10px] uppercase tracking-wider text-ink-soft mb-1.5">{label}</div>
                      {side.uploaded && side.dataUrl ? (
                        // eslint-disable-next-line @next/next/no-img-element
                        <img src={side.dataUrl} alt={label}
                          className="w-full rounded-sm border border-mist object-contain"
                          style={{ maxHeight: 160, background: "#F4F6F0" }} />
                      ) : (
                        <div className="h-28 bg-white border border-mist rounded-sm flex flex-col items-center justify-center gap-1.5">
                          <svg viewBox="0 0 24 24" fill="none" stroke="#5B6B63" strokeWidth="1.6" className="w-6 h-6">
                            <rect x="3" y="5" width="18" height="14" rx="2" /><circle cx="9" cy="10" r="2" />
                            <path d="M21 17l-5-5-4 4-2-2-5 5" />
                          </svg>
                          <span className="text-[10px] text-ink-soft font-mono truncate max-w-[100px] px-2 text-center">
                            {side.fileName || "Not uploaded"}
                          </span>
                        </div>
                      )}
                    </div>
                  ))}
                </div>
              </div>
              {selfie.dataUrl && (
                <div className="bg-white border border-mist rounded-md overflow-hidden">
                  <div className="px-5 pt-4 pb-2 font-mono text-xs uppercase tracking-widest text-gold-deep">Selfie</div>
                  {/* eslint-disable-next-line @next/next/no-img-element */}
                  <img src={selfie.dataUrl} alt="Selfie" className="w-full object-cover border-t border-mist" style={{ maxHeight: 280, background: "#1A2420" }} />
                </div>
              )}
              <div className="bg-sage border border-mist rounded-md p-5">
                <div className="font-mono text-xs uppercase tracking-widest text-gold-deep mb-3">Property authority</div>
                {[["Document type", propertyAuth.docType],["File", propertyAuth.fileName],["Owner verification", personal.role === "owner" ? "N/A" : propertyAuth.ownerOtpVerified ? "Verified ✓" : "Pending"]].map(([l, v]) => (
                  <div key={l as string} className="flex justify-between py-2 border-b border-mist last:border-b-0 text-sm">
                    <span className="text-ink-soft">{l}</span><span className="font-medium">{v}</span>
                  </div>
                ))}
              </div>
            </div>
            <label className="flex items-start gap-3 mb-6 cursor-pointer">
              <input type="checkbox" checked={agreed} onChange={(e) => setAgreed(e.target.checked)} className="w-4 h-4 mt-0.5 accent-forest shrink-0" />
              <span className="text-sm text-ink-soft">I confirm all information is accurate and I am authorised to list this property. I understand that false information may result in permanent account suspension.</span>
            </label>
            <div className="flex justify-between">
              <Btn variant="ghost" onClick={() => setStep("property-auth")}>← Back</Btn>
              <Btn onClick={submitStayKyc} disabled={!agreed || submitting}>{submitting ? "Submitting…" : "Submit KYC application"}</Btn>
            </div>
          </div>
        )}
      </div>

      {step !== "review" && (
        <p className="text-xs text-ink-soft text-center mt-4">Your progress is saved. You can return to this page to continue.</p>
      )}
    </div>
  );
}
