// kyc.jsx - post-signup verification gate.
// After someone creates a vault we ask for their address + a proof of identity,
// then Cova reviews the details for consistency (name / address / ID match) as a
// light KYC check. The address is saved to the profile so it flows onto every
// schedule of assets and policy certificate. Exposed as window.KycGate.
const { useState: useStateK } = React;

// Cova's consistency review — a transparent heuristic (no real document OCR in
// the prototype): checks the name is present, the address looks complete, the ID
// number is well-formed for its type, and a document was attached.
function reviewKyc({ userName, address, idNumber, docName, profile }) {
  const issues = [];
  if (!(userName || "").trim() || (userName || "").trim().length < 2) issues.push("we couldn't read a name on your account");
  if ((address || "").trim().length < 8) issues.push("your address looks incomplete, add street, area and city");
  const digits = (idNumber || "").replace(/\D/g, "");
  const idOk = profile === "business" ? digits.length >= 6 : digits.length === 11; // NIN = 11 digits
  if (!idOk) issues.push(profile === "business" ? "that RC number looks unusual" : "a Nigerian NIN should be 11 digits");
  if (!docName) issues.push("we didn't receive your ID document");
  return { status: issues.length === 0 ? "verified" : "review", issues };
}

function KycGate({ profile, userName, onDone, onCancel, reason }) {
  const isBiz = profile === "business";
  const idLabel = isBiz ? "CAC / RC number" : "National ID (NIN)";
  const [address, setAddress] = useStateK("");
  const [idNumber, setIdNumber] = useStateK("");
  const [docName, setDocName] = useStateK("");
  const [phase, setPhase] = useStateK("form"); // form | reviewing | done
  const [result, setResult] = useStateK(null);
  const [saving, setSaving] = useStateK(false);
  const first = (userName || "").trim().split(/\s+/)[0] || (isBiz ? "there" : "there");
  const ready = address.trim().length >= 6 && idNumber.trim() && docName;

  const submit = () => {
    if (!ready) return;
    setPhase("reviewing");
    // A short beat so Cova visibly "reviews", then persist the outcome.
    setTimeout(() => {
      const r = reviewKyc({ userName, address, idNumber, docName, profile });
      setResult(r);
      setSaving(true);
      const note = r.issues.length ? r.issues.join("; ") : "Name, address and ID are consistent.";
      const payload = {
        kyc: { status: r.status, note, idType: idLabel, idNumber: idNumber.trim(), idDocName: docName, address: address.trim() },
        address: address.trim(),
      };
      payload[isBiz ? "rcNumber" : "nin"] = idNumber.trim();
      fetch("/api/profile", { method: "PATCH", headers: { "Content-Type": "application/json" }, body: JSON.stringify(payload) })
        .catch(() => {})
        .finally(() => { setSaving(false); setPhase("done"); });
    }, 1100);
  };

  const finish = () => onDone && onDone({ address: address.trim(), status: result ? result.status : "review" });

  return (
    <div style={{ position: "fixed", inset: 0, zIndex: 400, background: "rgba(15,17,36,.55)", backdropFilter: "blur(4px)", display: "grid", placeItems: "center", padding: 20 }}>
      <div style={{ width: "100%", maxWidth: 480, borderRadius: 22, background: "var(--surface)", border: "1px solid var(--border)", boxShadow: "var(--shadow-lg)", overflow: "hidden", animation: "vc-fade-up .4s var(--ease) both" }}>
        {/* header */}
        <div style={{ display: "flex", alignItems: "center", gap: 12, padding: "18px 22px", borderBottom: "1px solid var(--border)" }}>
          <span style={{ display: "grid", placeItems: "center", width: 40, height: 40, borderRadius: 12, background: "var(--accent-soft)", color: "var(--accent)" }}><window.Icon name="shield" size={21} /></span>
          <div>
            <div className="display" style={{ fontSize: 18 }}>Verify your account</div>
            <div style={{ fontSize: 12.5, color: "var(--text-muted)" }}>A quick KYC step, it keeps your policies valid.</div>
          </div>
        </div>

        {phase === "form" && (
          <div style={{ padding: 22 }}>
            <p style={{ fontSize: 13.5, color: "var(--text-muted)", lineHeight: 1.55, marginBottom: 16 }}>
              {reason || <>Hi {first} 👋 I'm Cova. Before we protect anything, I just need to confirm who you are and where you're based. Your address goes on your schedules and policies.</>}
            </p>
            <KField label={isBiz ? "Registered business address" : "Residential address"} required>
              <textarea value={address} onChange={(e) => setAddress(e.target.value)} rows={2} placeholder="Street, area, city, state"
                style={{ width: "100%", resize: "none", border: "1.5px solid var(--border)", background: "var(--surface-2)", borderRadius: 11, padding: "10px 12px", fontSize: 14, color: "var(--text)", outline: "none", fontFamily: "inherit" }} />
            </KField>
            <KField label={idLabel} required>
              <input value={idNumber} onChange={(e) => setIdNumber(e.target.value)} placeholder={isBiz ? "e.g. RC 1234567" : "11-digit NIN"} inputMode="numeric"
                style={{ width: "100%", border: "1.5px solid var(--border)", background: "var(--surface-2)", borderRadius: 11, padding: "11px 12px", fontSize: 14, color: "var(--text)", outline: "none" }} />
            </KField>
            <KField label="Proof of identity" required hint={isBiz ? "CAC certificate, or a director's government ID" : "NIN slip, driver's licence, passport or voter's card"}>
              <label style={{ display: "flex", alignItems: "center", gap: 10, padding: "11px 12px", borderRadius: 11, border: "1.5px dashed var(--border)", background: "var(--surface-2)", cursor: "pointer", fontSize: 13.5, color: docName ? "var(--text)" : "var(--text-muted)", fontWeight: 600 }}>
                <window.Icon name={docName ? "check" : "upload"} size={16} style={{ color: docName ? "var(--success)" : "var(--text-faint)" }} />
                <span style={{ flex: 1, whiteSpace: "nowrap", overflow: "hidden", textOverflow: "ellipsis" }}>{docName || "Upload a photo or PDF"}</span>
                <input type="file" accept="image/*,.pdf" onChange={(e) => setDocName(e.target.files && e.target.files[0] ? e.target.files[0].name : "")} style={{ display: "none" }} />
              </label>
            </KField>
            <button onClick={submit} disabled={!ready} style={{
              marginTop: 6, width: "100%", padding: "12px 0", borderRadius: 999, fontSize: 14.5, fontWeight: 700, border: "none",
              background: ready ? "var(--accent)" : "var(--surface-3)", color: ready ? "#fff" : "var(--text-faint)", cursor: ready ? "pointer" : "default", transition: "all .2s",
            }}>Submit for review</button>
            {onCancel && <button onClick={onCancel} style={{ marginTop: 8, width: "100%", padding: "10px 0", borderRadius: 999, fontSize: 13.5, fontWeight: 700, border: "none", background: "transparent", color: "var(--text-muted)", cursor: "pointer" }}>Not now</button>}
            <div style={{ marginTop: 10, fontSize: 11.5, color: "var(--text-faint)", textAlign: "center" }}>Your details are encrypted and used only for verification.</div>
          </div>
        )}

        {phase === "reviewing" && (
          <div style={{ padding: "40px 22px", textAlign: "center" }}>
            <div style={{ display: "inline-flex", alignItems: "center", gap: 10, color: "var(--accent)", fontWeight: 700, fontSize: 14.5 }}>
              <span style={{ display: "grid", placeItems: "center", animation: "vc-spin 1s linear infinite" }}><window.Icon name="sparkle" size={20} /></span>
              Cova is reviewing your details…
            </div>
            <p style={{ marginTop: 10, fontSize: 13, color: "var(--text-muted)" }}>Checking your name, address and ID line up.</p>
          </div>
        )}

        {phase === "done" && result && (
          <div style={{ padding: 22 }}>
            <div style={{ display: "flex", alignItems: "flex-start", gap: 12, padding: 14, borderRadius: 14, background: result.status === "verified" ? "var(--success-soft)" : "var(--warning-soft)", border: "1px solid " + (result.status === "verified" ? "var(--success)" : "var(--warning)") }}>
              <window.Icon name={result.status === "verified" ? "check" : "alert"} size={20} style={{ color: result.status === "verified" ? "var(--success)" : "var(--warning)", flexShrink: 0, marginTop: 1 }} />
              <div style={{ fontSize: 13.5, lineHeight: 1.55, color: "var(--text)" }}>
                {result.status === "verified"
                  ? <>Thanks {first}, your name, address and {idLabel.toLowerCase()} all line up. <b>You're verified ✓</b> Your address is now on file and will appear on your schedules and policies.</>
                  : <>Thanks {first}. I've saved everything, but a couple of things need a second look: {result.issues.join("; ")}. You can continue for now, our team may reach out to confirm.</>}
              </div>
            </div>
            <button onClick={finish} disabled={saving} style={{
              marginTop: 16, width: "100%", padding: "12px 0", borderRadius: 999, fontSize: 14.5, fontWeight: 700, border: "none",
              background: "var(--accent)", color: "#fff", cursor: "pointer",
            }}>{saving ? "Saving…" : "Enter VaultCova"}</button>
          </div>
        )}
      </div>
    </div>
  );
}

function KField({ label, required, hint, children }) {
  return (
    <div style={{ marginBottom: 14 }}>
      <div style={{ fontSize: 12.5, fontWeight: 600, color: "var(--text-muted)", marginBottom: 6 }}>
        {label}{required && <span style={{ color: "var(--accent)" }}> *</span>}
      </div>
      {children}
      {hint && <div style={{ fontSize: 11.5, color: "var(--text-faint)", marginTop: 5 }}>{hint}</div>}
    </div>
  );
}

Object.assign(window, { KycGate });
