/* global React */
const { useState, useEffect, useMemo } = React;

// Simple icons (inline SVG, stroke-based)
const Ic = {
  arrow: (p) => (
    <svg
      width="18"
      height="18"
      viewBox="0 0 24 24"
      fill="none"
      stroke="currentColor"
      strokeWidth="2"
      strokeLinecap="round"
      strokeLinejoin="round"
      {...p}
    >
      <path d="M5 12h14M13 5l7 7-7 7" />
    </svg>
  ),
  arrowL: (p) => (
    <svg
      width="18"
      height="18"
      viewBox="0 0 24 24"
      fill="none"
      stroke="currentColor"
      strokeWidth="2"
      strokeLinecap="round"
      strokeLinejoin="round"
      {...p}
    >
      <path d="M19 12H5M11 5l-7 7 7 7" />
    </svg>
  ),
  check: (p) => (
    <svg
      width="14"
      height="14"
      viewBox="0 0 24 24"
      fill="none"
      stroke="currentColor"
      strokeWidth="3"
      strokeLinecap="round"
      strokeLinejoin="round"
      {...p}
    >
      <path d="M20 6L9 17l-5-5" />
    </svg>
  ),
  eye: (p) => (
    <svg
      width="15"
      height="15"
      viewBox="0 0 24 24"
      fill="none"
      stroke="currentColor"
      strokeWidth="1.8"
      strokeLinecap="round"
      strokeLinejoin="round"
      {...p}
    >
      <path d="M1 12s4-8 11-8 11 8 11 8-4 8-11 8-11-8-11-8z" />
      <circle cx="12" cy="12" r="3" />
    </svg>
  ),
  chev: (p) => (
    <svg
      width="12"
      height="12"
      viewBox="0 0 24 24"
      fill="none"
      stroke="currentColor"
      strokeWidth="2.5"
      strokeLinecap="round"
      strokeLinejoin="round"
      {...p}
    >
      <path d="M6 9l6 6 6-6" />
    </svg>
  ),
  back: (p) => (
    <svg
      width="16"
      height="16"
      viewBox="0 0 24 24"
      fill="none"
      stroke="currentColor"
      strokeWidth="2.2"
      strokeLinecap="round"
      strokeLinejoin="round"
      {...p}
    >
      <path d="M15 18l-6-6 6-6" />
    </svg>
  ),
  user: (p) => (
    <svg
      width="22"
      height="22"
      viewBox="0 0 24 24"
      fill="none"
      stroke="currentColor"
      strokeWidth="1.8"
      strokeLinecap="round"
      strokeLinejoin="round"
      {...p}
    >
      <circle cx="12" cy="8" r="4" />
      <path d="M3 21c2-4 5-6 9-6s7 2 9 6" />
    </svg>
  ),
  briefcase: (p) => (
    <svg
      width="22"
      height="22"
      viewBox="0 0 24 24"
      fill="none"
      stroke="currentColor"
      strokeWidth="1.8"
      strokeLinecap="round"
      strokeLinejoin="round"
      {...p}
    >
      <rect x="3" y="7" width="18" height="13" rx="2" />
      <path d="M8 7V5a2 2 0 012-2h4a2 2 0 012 2v2" />
    </svg>
  ),
  camera: (p) => (
    <svg
      width="18"
      height="18"
      viewBox="0 0 24 24"
      fill="none"
      stroke="currentColor"
      strokeWidth="1.8"
      strokeLinecap="round"
      strokeLinejoin="round"
      {...p}
    >
      <path d="M23 19V8a2 2 0 00-2-2h-3.2l-1.8-2.4A2 2 0 0014.4 3H9.6a2 2 0 00-1.6.8L6.2 6H3a2 2 0 00-2 2v11a2 2 0 002 2h18a2 2 0 002-2z" />
      <circle cx="12" cy="13" r="4" />
    </svg>
  ),
  upload: (p) => (
    <svg
      width="18"
      height="18"
      viewBox="0 0 24 24"
      fill="none"
      stroke="currentColor"
      strokeWidth="1.8"
      strokeLinecap="round"
      strokeLinejoin="round"
      {...p}
    >
      <path d="M12 3v12m0-12l-4 4m4-4l4 4M5 21h14" />
    </svg>
  ),
  signal: (p) => (
    <svg width="13" height="9" viewBox="0 0 17 11" fill="currentColor" {...p}>
      <rect x="0" y="7" width="3" height="4" rx="0.5" />
      <rect x="4.5" y="5" width="3" height="6" rx="0.5" />
      <rect x="9" y="2.5" width="3" height="8.5" rx="0.5" />
      <rect x="13.5" y="0" width="3" height="11" rx="0.5" />
    </svg>
  ),
  wifi: (p) => (
    <svg
      width="14"
      height="10"
      viewBox="0 0 16 12"
      fill="none"
      stroke="currentColor"
      strokeWidth="1.4"
      strokeLinecap="round"
      {...p}
    >
      <path d="M1 4.5C3 2.5 5.5 1 8 1s5 1.5 7 3.5M3.5 7C5 5.5 6.5 4.8 8 4.8S11 5.5 12.5 7M6 9.5c.5-.5 1.2-.8 2-.8s1.5.3 2 .8" />
      <circle cx="8" cy="10.8" r=".8" fill="currentColor" />
    </svg>
  ),
  battery: (p) => (
    <svg
      width="22"
      height="10"
      viewBox="0 0 26 12"
      fill="none"
      stroke="currentColor"
      strokeWidth="1"
      {...p}
    >
      <rect x="1" y="1" width="22" height="10" rx="2.5" />
      <rect
        x="24"
        y="4"
        width="1.5"
        height="4"
        rx=".5"
        fill="currentColor"
        stroke="none"
      />
      <rect
        x="3"
        y="3"
        width="18"
        height="6"
        rx="1.5"
        fill="currentColor"
        stroke="none"
      />
    </svg>
  ),
};

// Phone status bar
function StatusBar() {
  return (
    <div className="status-bar">
      <span>9:41</span>
      <div className="right">
        <Ic.signal />
        <Ic.wifi />
        <Ic.battery />
      </div>
    </div>
  );
}

// Small contextual chip used on SME screens to distinguish owner-side vs business-side data capture
function AboutChip({ who }) {
  const map = {
    owner: { icon: "👤", text: "Owner" },
    business: { icon: "🏢", text: "Business" },
  };
  const it = map[who];
  if (!it) return null;
  return (
    <div className="about-chip">
      <span className="about-chip-dot">·</span>
      <span className="about-chip-ic" aria-hidden="true">
        {it.icon}
      </span>
      <span>{it.text}</span>
      <span className="about-chip-dot">·</span>
    </div>
  );
}

// Screen shell
function Shell({ title, onBack, progress, children, footer }) {
  return (
    <div className="scr">
      <StatusBar />
      <div className="scr-head">
        {onBack !== false && (
          <div className="back">
            <Ic.back />
          </div>
        )}
        <div className="title">{title}</div>
      </div>
      {progress != null && (
        <div className="scr-progress">
          <div className="bar" style={{ width: progress + "%" }} />
        </div>
      )}
      <div className="scr-body">{children}</div>
      {footer && <div className="scr-foot">{footer}</div>}
    </div>
  );
}

// =========== ENTRY ===========

function EntryType({ ctx, setCtx }) {
  return (
    <Shell
      title="Open an account"
      onBack={false}
      progress={10}
      footer={
        <button
          className="btn btn-primary"
          onClick={() => ctx.next()}
          disabled={!ctx.customerType}
        >
          Continue <Ic.arrow />
        </button>
      }
    >
      <div className="scr-h1" style={{ textWrap: "pretty" }}>
        Welcome. What brings you here today?
      </div>
      <div className="scr-lede">
        Tell us a little about yourself so we can set you up right.
      </div>
      <div style={{ display: "grid", gap: 10, marginTop: 6 }}>
        <button
          className={
            "choice" + (ctx.customerType === "individual" ? " selected" : "")
          }
          onClick={() => setCtx({ customerType: "individual" })}
        >
          <div className="ic">
            <Ic.user />
          </div>
          <div className="ch-title">I'm opening for myself</div>
          <div className="ch-sub">
            Personal account · Wallet, Basic or Standard
          </div>
        </button>
        <button
          className={
            "choice" + (ctx.customerType === "business" ? " selected" : "")
          }
          onClick={() => setCtx({ customerType: "business" })}
        >
          <div className="ic">
            <Ic.briefcase />
          </div>
          <div className="ch-title">I'm opening for a business</div>
          <div className="ch-sub">
            Business Account · Simple or Complex structures
          </div>
        </button>
      </div>
    </Shell>
  );
}

const INDIV_PILLARS = [
  { k: "transact", emoji: "💸", title: "Transact", sub: "Send, receive, pay" },
  { k: "save", emoji: "🏦", title: "Save", sub: "Savings & term deposits" },
  {
    k: "borrow",
    emoji: "💳",
    title: "Borrow",
    sub: "Cards, loans, home & vehicle finance",
  },
  { k: "insure", emoji: "🛡️", title: "Insure", sub: "Motor & family cover" },
];
const BIZ_PILLARS = [
  {
    k: "transact",
    emoji: "💸",
    title: "Payments",
    sub: "Bulk payments, transfers, mobile money",
  },
  {
    k: "collect",
    emoji: "🧾",
    title: "Collections",
    sub: "POS, cash deposits, reference-based",
  },
  {
    k: "cashmgmt",
    emoji: "🔁",
    title: "Cash management",
    sub: "Cash sweeping",
  },
  {
    k: "borrow",
    emoji: "💳",
    title: "Borrow",
    sub: "Working capital, asset finance",
  },
  {
    k: "trade",
    emoji: "🌐",
    title: "Trade",
    sub: "Letters of credit, guarantees",
  },
  {
    k: "invest",
    emoji: "📈",
    title: "Invest",
    sub: "Treasury bills, bonds, shares",
  },
  {
    k: "advisory",
    emoji: "🛡️",
    title: "Insure & advise",
    sub: "Insurance, advisory services",
  },
];

const SUB_INTENTS = {
  individual: {
    transact: [
      "Send money",
      "Receive my salary",
      "Pay bills",
      "Buy airtime / data",
      "Card payments",
      "Send to mobile money",
    ],
    save: ["Savings account", "Term deposit (MZN)", "Term deposit (Foreign)"],
    borrow: [
      "Credit card",
      "Consumer loan",
      "Vehicle / asset finance",
      "Home loan",
    ],
    insure: ["Motor insurance", "Family assistance plan"],
  },
  business: {
    transact: [
      "Bulk payments",
      "Supplier transfers",
      "Mobile money",
      "Pay employees",
    ],
    collect: [
      "POS devices",
      "Deposita box (cash deposits)",
      "Reference-based payments",
    ],
    cashmgmt: ["Cash sweeping across accounts"],
    borrow: ["Working capital", "Asset-based finance"],
    trade: ["Letters of credit", "Guarantees"],
    invest: ["Treasury bills", "Bonds", "Shares"],
    advisory: ["Business insurance", "Advisory services"],
  },
};

function EntryIntents({ ctx, setCtx }) {
  const pillars = ctx.customerType === "business" ? BIZ_PILLARS : INDIV_PILLARS;
  const [openPillar, setOpenPillar] = useState("transact");
  const selectedPillars = ctx.pillars || {};
  const subs = SUB_INTENTS[ctx.customerType || "individual"];

  const toggleSub = (k, sub) => {
    const cur = selectedPillars[k]?.subs || [];
    const next = cur.includes(sub)
      ? cur.filter((s) => s !== sub)
      : [...cur, sub];
    setCtx({ pillars: { ...selectedPillars, [k]: { subs: next } } });
  };
  const anySelected =
    Object.keys(selectedPillars).filter((k) => selectedPillars[k].subs?.length)
      .length > 0;

  return (
    <Shell
      title="What do you want to do?"
      progress={30}
      footer={
        <button
          className="btn btn-primary"
          onClick={() => ctx.next()}
          disabled={!anySelected}
        >
          See my recommendation <Ic.arrow />
        </button>
      }
    >
      <div className="scr-h2">Pick everything that sounds like you.</div>
      <div className="scr-lede" style={{ marginTop: -4 }}>
        Tap a section to pick your goals. You can choose from more than one.
      </div>
      <div className="accordion">
        {pillars.map((p) => {
          const isOpen = openPillar === p.k;
          const selected = selectedPillars[p.k]?.subs || [];
          const list = subs[p.k] || [];
          return (
            <div
              key={p.k}
              className={
                "acc-row" +
                (isOpen ? " open" : "") +
                (p.soon ? " soon" : "") +
                (selected.length ? " has-sel" : "")
              }
            >
              <button
                className="acc-head"
                onClick={() => setOpenPillar(isOpen ? null : p.k)}
              >
                <span className="acc-emoji">{p.emoji}</span>
                <span className="acc-title">{p.title}</span>
                {p.soon && <span className="acc-soon">Coming soon</span>}
                {!p.soon && selected.length > 0 && (
                  <span className="acc-count">{selected.length}</span>
                )}
                <span
                  className="acc-chev"
                  style={{ transform: isOpen ? "rotate(180deg)" : "none" }}
                >
                  <Ic.chev />
                </span>
              </button>
              {isOpen && !p.soon && list.length > 0 && (
                <div className="acc-body fade-in">
                  {list.map((s) => {
                    const on = selected.includes(s);
                    return (
                      <label
                        key={s}
                        className={"acc-item" + (on ? " on" : "")}
                        onClick={() => toggleSub(p.k, s)}
                      >
                        <span className="check">{on && <Ic.check />}</span>
                        <span>{s}</span>
                      </label>
                    );
                  })}
                </div>
              )}
              {isOpen && p.soon && (
                <div className="acc-body fade-in">
                  <div className="acc-soon-note">
                    We're not offering this yet. Tap to let us know you're
                    interested — we'll notify you when it's ready.
                  </div>
                  <button
                    className="acc-notify"
                    onClick={() =>
                      setCtx({
                        pillars: {
                          ...selectedPillars,
                          [p.k]: { interested: true },
                        },
                      })
                    }
                  >
                    {selectedPillars[p.k]?.interested
                      ? "✓ We'll let you know"
                      : "Notify me"}
                  </button>
                </div>
              )}
            </div>
          );
        })}
      </div>
    </Shell>
  );
}

function EntryReco({ ctx }) {
  const pillars = ctx.pillars || {};
  let tier = "Wallet",
    tierKey = "wallet";
  let reason =
    "Everything you want to do today fits on a Wallet — simple and fast.";
  if (ctx.customerType === "business") {
    const complexEntity = ["SA", "Associação", "Outro"].includes(
      ctx.businessEntityType,
    );
    const multiSig = ctx.businessSignatories === "many";
    if (complexEntity || multiSig) {
      tier = "Business Complex";
      tierKey = "sme-complex";
      reason = complexEntity
        ? "Your entity type needs multi-party governance — Business Complex is the right fit. It's coming soon, we'll keep you posted."
        : "You have more than one signatory — Business Complex handles shared authorisations. It's coming soon, we'll keep you posted.";
    } else {
      tier = "Business Lite";
      tierKey = "sme";
      reason =
        "For single-signatory SMEs — Business Lite covers payments, collections, and credit in one place.";
    }
  } else {
    const any = (k) => !!pillars[k]?.subs?.length;
    const tx = pillars.transact?.subs || [];
    const wantsSalary = tx.includes("Receive my salary");
    if (any("borrow")) {
      tier = "Standard";
      tierKey = "standard-low";
      reason =
        "You asked about credit, which needs a Standard account — it covers everything else you selected too.";
    } else if (wantsSalary) {
      tier = "Standard";
      tierKey = "standard-low";
      reason =
        "You want to receive your salary — the Salary Account on Standard is the right fit.";
    } else if (any("save")) {
      tier = "Basic";
      tierKey = "basic";
      reason =
        "Saving money needs a Basic account. Easy to upgrade to Standard when you want credit.";
    }
  }
  const chosenChips = Object.entries(pillars)
    .filter(([, v]) => v.subs?.length)
    .map(([k]) => k);

  return (
    <Shell
      title="Your recommendation"
      progress={50}
      footer={
        <>
          <button
            className="btn btn-primary"
            onClick={() =>
              tierKey !== "sme-complex" && ctx.jumpToJourney(tierKey)
            }
            disabled={tierKey === "sme-complex"}
          >
            {tierKey === "sme-complex" ? (
              "Join the Business Complex waitlist"
            ) : (
              <>
                Continue with {tier} <Ic.arrow />
              </>
            )}
          </button>
          <button className="btn btn-text" onClick={ctx.next}>
            See other options
          </button>
        </>
      }
    >
      <div className="reco">
        <div className="badge">
          {tierKey === "sme-complex" ? "Coming soon" : "Best match"}
        </div>
        <div className="tier">{tier} account</div>
        <div className="why">{reason}</div>
      </div>
      {chosenChips.length > 0 && (
        <>
          <div
            style={{
              fontSize: 11,
              color: "var(--ink-3)",
              letterSpacing: 0.06,
              textTransform: "uppercase",
              marginTop: 4,
            }}
          >
            Based on
          </div>
          <div className="chips">
            {chosenChips.map((k) => (
              <span key={k} className="chip">
                {k[0].toUpperCase() + k.slice(1)}
              </span>
            ))}
          </div>
        </>
      )}
      <div style={{ flex: 1 }} />
    </Shell>
  );
}

const COMPLEX_ENTITY_TYPES = ["SA", "Associação", "Outro"];

function recommendedTier(ctx) {
  if (ctx.customerType === "business") {
    const complexEntity = COMPLEX_ENTITY_TYPES.includes(ctx.businessEntityType);
    const multiSig = ctx.businessSignatories === "many";
    if (complexEntity || multiSig) return "sme-complex";
    return "sme";
  }
  const pillars = ctx.pillars || {};
  const any = (k) => !!pillars[k]?.subs?.length;
  const tx = pillars.transact?.subs || [];
  const wantsSalary = tx.includes("Receive my salary");
  if (any("borrow")) return "standard-low";
  if (wantsSalary) return "standard-low";
  if (any("save")) return "basic";
  return "wallet";
}

function EntryOptions({ ctx }) {
  const rec = recommendedTier(ctx);
  const [picked, setPicked] = useState(rec);
  const individualOpts = [
    {
      key: "wallet",
      title: "Wallet",
      sub: "Digital-only · no card",
      preview: ctx.opsState === "initial",
    },
    { key: "basic", title: "Basic", sub: "Card eligible · everyday banking" },
    {
      key: "standard-low",
      title: "Standard",
      sub: "Full-service · credit, saving, salary, premium",
    },
  ];
  const isComplexEntity =
    COMPLEX_ENTITY_TYPES.includes(ctx.businessEntityType) ||
    ctx.businessSignatories === "many";
  const businessOpts = [
    {
      key: "sme",
      title: "Business Lite",
      sub: isComplexEntity
        ? "Not available for your entity type"
        : "Single-signatory SMEs · Simple structure",
      comingSoon: isComplexEntity,
    },
    {
      key: "sme-complex",
      title: "Business Complex",
      sub: "Multiple signatories, group structures",
      comingSoon: true,
    },
  ];
  const row = (o) => {
    const selected = o.key === picked;
    return (
      <button
        key={o.key}
        className={"choice" + (selected ? " selected" : "")}
        disabled={!!o.comingSoon}
        onClick={() => !o.comingSoon && setPicked(o.key)}
        style={{
          flexDirection: "row",
          alignItems: "center",
          gap: 12,
          opacity: o.comingSoon ? 0.55 : 1,
          cursor: o.comingSoon ? "not-allowed" : "pointer",
        }}
      >
        <div style={{ flex: 1 }}>
          <div
            className="ch-title"
            style={{
              fontSize: 14,
              display: "flex",
              alignItems: "center",
              gap: 8,
              flexWrap: "nowrap",
            }}
          >
            <span style={{ minWidth: 0 }}>{o.title}</span>
            {o.key === rec && (
              <span
                className="acc-soon"
                style={{
                  background: "var(--teal-soft)",
                  color: "var(--teal-deep)",
                }}
              >
                Recommended
              </span>
            )}
            {o.preview && o.key !== rec && (
              <span
                className="acc-soon"
                style={{
                  background: "var(--teal-soft)",
                  color: "var(--teal-deep)",
                }}
              >
                Preview
              </span>
            )}
            {o.comingSoon && <span className="acc-soon">Coming soon</span>}
          </div>
          <div className="ch-sub">{o.sub}</div>
        </div>
        {selected && <Ic.check />}
      </button>
    );
  };
  const isBiz = ctx.customerType === "business";
  const pickedTitle =
    individualOpts.concat(businessOpts).find((o) => o.key === picked)?.title ||
    "";
  const waitlist = picked === "sme-complex";
  return (
    <Shell
      title={isBiz ? "Business accounts" : "Personal accounts"}
      progress={ctx.progress}
      footer={
        <>
          <button
            className="btn btn-primary"
            onClick={() => !waitlist && ctx.jumpToJourney(picked)}
            disabled={waitlist}
          >
            {waitlist ? (
              "Join the Business Complex waitlist"
            ) : (
              <>
                Continue with {pickedTitle} <Ic.arrow />
              </>
            )}
          </button>
          <button className="btn btn-text" onClick={ctx.prev}>
            Back to recommendation
          </button>
        </>
      }
    >
      <div className="scr-h1">Choose the right fit</div>
      <div className="scr-lede">
        Compare the full range. You can always upgrade later.
      </div>
      {!isBiz && (
        <>
          <div
            style={{
              fontSize: 10,
              color: "var(--ink-3)",
              letterSpacing: 0.06,
              textTransform: "uppercase",
              marginTop: 4,
            }}
          >
            Individual
          </div>
          <div style={{ display: "flex", flexDirection: "column", gap: 8 }}>
            {individualOpts.map(row)}
          </div>
        </>
      )}
      {isBiz && (
        <>
          <div
            style={{
              fontSize: 10,
              color: "var(--ink-3)",
              letterSpacing: 0.06,
              textTransform: "uppercase",
              marginTop: 4,
            }}
          >
            Business
          </div>
          <div style={{ display: "flex", flexDirection: "column", gap: 8 }}>
            {businessOpts.map(row)}
          </div>
        </>
      )}
    </Shell>
  );
}

// =========== JOURNEY SCREENS ===========

function Identity({ ctx }) {
  const isSme = ctx.journey.key === "sme";
  return (
    <Shell
      title="Verify your number"
      progress={ctx.progress}
      footer={
        <button className="btn btn-primary" onClick={ctx.next}>
          Continue <Ic.arrow />
        </button>
      }
    >
      {isSme && <AboutChip who="owner" />}
      <div className="scr-h1">Let's get started</div>
      <div className="scr-lede">
        We'll text you a code to verify your number.
      </div>
      <div
        style={{
          display: "flex",
          flexDirection: "column",
          gap: 10,
          marginTop: 4,
        }}
      >
        <div className="field">
          <label>Phone number</label>
          <div className="input filled">+258 84 123 4567</div>
        </div>
        <div className="field">
          <label>Verification code</label>
          <div className="input filled">
            4 · 8 · 2 · 1 · 9 · 3{" "}
            <span
              style={{
                marginLeft: "auto",
                fontSize: 11,
                color: "var(--green)",
                fontWeight: 600,
              }}
            >
              ✓ Verified
            </span>
          </div>
        </div>
      </div>
    </Shell>
  );
}

function IdentityDetails({ ctx }) {
  const isSme = ctx.journey.key === "sme";
  return (
    <Shell
      title="Your details"
      progress={ctx.progress}
      footer={
        <button className="btn btn-primary" onClick={ctx.next}>
          Continue <Ic.arrow />
        </button>
      }
    >
      {isSme && <AboutChip who="owner" />}
      <div className="scr-h1">Tell us about you</div>
      <div className="scr-lede">
        Enter your details as they appear on your official documents and include
        a valid email address for communication.
      </div>
      <div
        style={{
          display: "flex",
          flexDirection: "column",
          gap: 10,
          marginTop: 4,
        }}
      >
        <div className="field">
          <label>Full name</label>
          <div className="input filled">Dércia Magaia</div>
        </div>
        <div className="field">
          <label>Email</label>
          <div className="input filled">dercia.magaia@bank.co.mz</div>
        </div>
        <div
          style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 8 }}
        >
          <div className="field">
            <label>Date of birth</label>
            <div className="input filled">12 · 06 · 1992</div>
          </div>
          <div className="field">
            <label>ID number</label>
            <div className="input filled">110619920M4</div>
          </div>
        </div>
      </div>
    </Shell>
  );
}

function IdCapture({ ctx }) {
  const isSme = ctx.journey.key === "sme";
  return (
    <Shell
      title="Verify your ID"
      progress={ctx.progress}
      footer={
        <button className="btn btn-primary" onClick={ctx.next}>
          Looks right — continue <Ic.arrow />
        </button>
      }
    >
      {isSme && <AboutChip who="owner" />}
      <div className="scr-h1">Photograph your ID</div>
      <div className="scr-lede">Make sure all four corners are visible.</div>
      <div className="id-card" style={{ marginTop: 4 }}>
        <div
          style={{
            display: "flex",
            justifyContent: "space-between",
            alignItems: "flex-start",
          }}
        >
          <div
            style={{
              fontSize: 10,
              color: "var(--teal-deep)",
              fontWeight: 600,
              letterSpacing: 0.08,
            }}
          >
            REPÚBLICA DE MOÇAMBIQUE
          </div>
          <div className="ocr-pill">
            <span className="pulse" />
            OCR
          </div>
        </div>
        <div
          className="chip"
          style={{
            width: "fit-content",
            background: "rgba(0,163,161,0.1)",
            color: "var(--teal-deep)",
          }}
        >
          D.M.
        </div>
        <div className="rows">
          <div className="row mid" />
          <div className="row" />
          <div className="row short" />
        </div>
      </div>
      <div
        style={{
          display: "flex",
          flexDirection: "column",
          gap: 6,
          marginTop: 4,
        }}
      >
        <div
          style={{
            fontSize: 11,
            color: "var(--ink-3)",
            textTransform: "uppercase",
            letterSpacing: 0.08,
            fontWeight: 600,
          }}
        >
          We found
        </div>
        <div className="details-card">
          <div className="dline">
            <span className="k">ID number</span>
            <span className="v">110619920M4</span>
          </div>
          <div className="dline">
            <span className="k">Full name</span>
            <span className="v">Dércia Magaia</span>
          </div>
          <div className="dline">
            <span className="k">Date of birth</span>
            <span className="v">12/06/1992</span>
          </div>
          <div className="dline">
            <span className="k">Valid until</span>
            <span className="v">03/2032</span>
          </div>
          <div className="dline">
            <span className="k">Address</span>
            <span
              className="v"
              style={{ textAlign: "right", flex: 1, marginLeft: 12 }}
            >
              Av. Marginal, Maputo
            </span>
          </div>
        </div>
      </div>
    </Shell>
  );
}

function Liveness({ ctx }) {
  const isSme = ctx.journey.key === "sme";
  return (
    <Shell
      title="Quick selfie check"
      progress={ctx.progress}
      footer={
        <button className="btn btn-primary" onClick={ctx.next}>
          Done — continue <Ic.arrow />
        </button>
      }
    >
      {isSme && <AboutChip who="owner" />}
      <div className="scr-h1">Look into the camera</div>
      <div className="scr-lede">
        Centre your face in the circle and blink when prompted.
      </div>
      <div
        className="liveness"
        style={{ borderRadius: 20, marginTop: 4, minHeight: 280 }}
      >
        <div className="ring">
          <div className="scanline" />
          <div className="face">
            <Ic.user />
          </div>
        </div>
        <div
          style={{ fontSize: 12, color: "var(--teal-deep)", fontWeight: 600 }}
        >
          ✓ Match detected
        </div>
      </div>
    </Shell>
  );
}

function Nuit({ ctx }) {
  const isTarget = ctx.opsState === "target";
  const isSme = ctx.journey.key === "sme";
  const initialBody = (
    <>
      <div className="scr-h1">Upload your NUIT</div>
      <div className="scr-lede">
        Take a photo of your NUIT card or upload a PDF.
      </div>
      <button
        className="choice"
        style={{ alignItems: "center", flexDirection: "row", gap: 12 }}
      >
        <div className="ic">
          <Ic.upload />
        </div>
        <div style={{ flex: 1 }}>
          <div className="ch-title" style={{ fontSize: 14 }}>
            NUIT card.jpg
          </div>
          <div className="ch-sub">Uploaded · photo</div>
        </div>
        <div style={{ color: "var(--green)" }}>
          <Ic.check />
        </div>
      </button>
      <div style={{ fontSize: 11, color: "var(--ink-3)" }}>
        You can skip and add it anytime from your profile.
      </div>
    </>
  );
  if (isTarget) {
    return (
      <Shell
        title="Tax ID (NUIT)"
        progress={ctx.progress}
        footer={
          <button className="btn btn-primary" onClick={ctx.next}>
            Continue <Ic.arrow />
          </button>
        }
      >
        {isSme && <AboutChip who="owner" />}
        <div
          style={{
            position: "relative",
            display: "flex",
            flexDirection: "column",
            gap: 10,
            flex: 1,
          }}
        >
          <div
            style={{
              opacity: 0.35,
              pointerEvents: "none",
              display: "flex",
              flexDirection: "column",
              gap: 10,
            }}
          >
            {initialBody}
          </div>
          <div className="nuit-auto-overlay">
            <div className="nuit-auto-title">
              NUIT retrieved from Tax Authority
            </div>
            <div className="nuit-auto-chip">✓ 110 485 229</div>
            <div className="nuit-auto-sub">No upload needed.</div>
          </div>
        </div>
      </Shell>
    );
  }
  return (
    <Shell
      title="Tax ID (NUIT)"
      progress={ctx.progress}
      footer={
        <>
          <button className="btn btn-primary" onClick={ctx.next}>
            Continue <Ic.arrow />
          </button>
          <button className="btn btn-text" onClick={ctx.next}>
            Skip — I'll add it later
          </button>
        </>
      }
    >
      {isSme && <AboutChip who="owner" />}
      {initialBody}
    </Shell>
  );
}

// Review & accept (FIND + T&Cs + Data consent)
function Consent({ ctx }) {
  const [accepted, setAccepted] = useState({
    find: false,
    terms: false,
    data: false,
  });
  const [emailCopies, setEmailCopies] = useState(true);
  const [open, setOpen] = useState(null);
  const docs = [
    {
      k: "find",
      title: "FIND",
      sub: "Ficha de Informação Normativa de Depósito — key facts (fees, interest, charges)",
      body: "The FIND is a standard deposit-product key-facts sheet mandated by the Central Bank. It sets out the account's interest rate, minimum balance, fees and charges, withdrawal and closure conditions, and channel availability — so you can compare products on like-for-like terms before you sign.",
    },
    {
      k: "terms",
      title: "Terms & Conditions",
      sub: "General banking terms",
      body: "Your account operates under the bank's standard terms. Key points: fees and charges are disclosed up-front, transactions are processed per Central Bank rails, and we'll notify you at least 30 days before any change to pricing.",
    },
    {
      k: "data",
      title: "Data processing consent",
      sub: "Permission to process your information",
      body: "You consent to the bank processing your personal data for account opening, fraud prevention, credit assessment, regulatory reporting, and delivering the services you've asked for. You can withdraw consent at any time by contacting us or through your profile settings.",
    },
  ];
  const allAccepted = accepted.find && accepted.terms && accepted.data;
  const isSme = ctx.journey.key === "sme";
  return (
    <Shell
      title="Review & accept"
      progress={ctx.progress}
      footer={
        <button
          className="btn btn-primary"
          onClick={ctx.next}
          disabled={!allAccepted}
        >
          Continue <Ic.arrow />
        </button>
      }
    >
      {isSme && <AboutChip who="owner" />}
      <div className="scr-h1">Before we start</div>
      <div className="scr-lede">
        Please read and accept the following. You can open each one to read it
        in full.
      </div>
      <div
        style={{
          display: "flex",
          flexDirection: "column",
          gap: 8,
          marginTop: 2,
        }}
      >
        {docs.map((d) => {
          const isOpen = open === d.k;
          const on = accepted[d.k];
          return (
            <div key={d.k} className={"doc-row" + (on ? " accepted" : "")}>
              <button
                className="doc-head"
                onClick={() => setOpen(isOpen ? null : d.k)}
              >
                <div style={{ flex: 1 }}>
                  <div className="doc-title">{d.title}</div>
                  <div className="doc-sub">{d.sub}</div>
                </div>
                <span
                  className="doc-chev"
                  style={{ transform: isOpen ? "rotate(180deg)" : "none" }}
                >
                  <Ic.chev />
                </span>
              </button>
              {isOpen && <div className="doc-body fade-in">{d.body}</div>}
              <label
                className="doc-accept"
                onClick={(e) => {
                  e.preventDefault();
                  setAccepted((a) => ({ ...a, [d.k]: !a[d.k] }));
                }}
              >
                <span className={"check-box" + (on ? " on" : "")}>
                  {on && <Ic.check />}
                </span>
                <span>I have read and accept</span>
              </label>
            </div>
          );
        })}
      </div>
      <label
        className="doc-accept"
        style={{ marginTop: 4 }}
        onClick={(e) => {
          e.preventDefault();
          setEmailCopies((v) => !v);
        }}
      >
        <span className={"check-box" + (emailCopies ? " on" : "")}>
          {emailCopies && <Ic.check />}
        </span>
        <span style={{ fontSize: 12 }}>Email me copies of these documents</span>
      </label>
    </Shell>
  );
}

// Digital signature screen — finger-drawn
function Signature({ ctx }) {
  const canvasRef = React.useRef(null);
  const [hasSignature, setHasSignature] = useState(false);
  const drawing = React.useRef(false);
  const lastPt = React.useRef(null);

  useEffect(() => {
    const c = canvasRef.current;
    if (!c) return;
    const rect = c.getBoundingClientRect();
    c.width = rect.width * devicePixelRatio;
    c.height = rect.height * devicePixelRatio;
    const g = c.getContext("2d");
    g.scale(devicePixelRatio, devicePixelRatio);
    g.lineCap = "round";
    g.lineJoin = "round";
    g.lineWidth = 2.2;
    g.strokeStyle = "#0E1E1E";
  }, []);

  const pt = (e) => {
    const r = canvasRef.current.getBoundingClientRect();
    const t = e.touches?.[0] ?? e;
    return { x: t.clientX - r.left, y: t.clientY - r.top };
  };
  const start = (e) => {
    e.preventDefault();
    drawing.current = true;
    lastPt.current = pt(e);
  };
  const move = (e) => {
    if (!drawing.current) return;
    e.preventDefault();
    const g = canvasRef.current.getContext("2d");
    const p = pt(e);
    g.beginPath();
    g.moveTo(lastPt.current.x, lastPt.current.y);
    g.lineTo(p.x, p.y);
    g.stroke();
    lastPt.current = p;
    if (!hasSignature) setHasSignature(true);
  };
  const end = () => {
    drawing.current = false;
  };
  const clear = () => {
    const c = canvasRef.current;
    const g = c.getContext("2d");
    g.clearRect(0, 0, c.width, c.height);
    setHasSignature(false);
  };

  const isSme = ctx.journey.key === "sme";
  return (
    <Shell
      title="Digital signature"
      progress={ctx.progress}
      footer={
        <>
          <button
            className="btn btn-primary"
            onClick={ctx.next}
            disabled={!hasSignature}
          >
            Sign and continue <Ic.arrow />
          </button>
          <button className="btn btn-text" onClick={ctx.next}>
            Skip — I'll sign later
          </button>
        </>
      }
    >
      {isSme && <AboutChip who="owner" />}
      <div className="scr-h1">Please sign to confirm</div>
      <div className="scr-lede">
        Your signature confirms you've read and agree to the documents on the
        previous screen.
      </div>
      <div className="sig-wrap">
        <canvas
          ref={canvasRef}
          onMouseDown={start}
          onMouseMove={move}
          onMouseUp={end}
          onMouseLeave={end}
          onTouchStart={start}
          onTouchMove={move}
          onTouchEnd={end}
        />
        {!hasSignature && (
          <div className="sig-hint">Sign here with your finger</div>
        )}
        <div className="sig-line" />
      </div>
      <div
        style={{
          display: "flex",
          justifyContent: "space-between",
          alignItems: "center",
          fontSize: 11,
          color: "var(--ink-3)",
        }}
      >
        <span>{hasSignature ? "✓ Signed" : "Use your finger on the line"}</span>
        <button
          className="btn-text"
          style={{ padding: "4px 8px", fontSize: 12 }}
          onClick={clear}
        >
          Clear
        </button>
      </div>
    </Shell>
  );
}

// Silent "risk-scoring" step — no visible phone screen (just a wait; backstage shows engine)
function RiskScoring({ ctx }) {
  return (
    <Shell
      title="One moment"
      progress={ctx.progress}
      footer={
        <button className="btn btn-primary" onClick={ctx.next}>
          Continue <Ic.arrow />
        </button>
      }
    >
      <div className="decisioning" style={{ gap: 12 }}>
        <div className="spinner" />
        <div className="scr-h2" style={{ textAlign: "center" }}>
          Just a second…
        </div>
        <div
          className="scr-lede"
          style={{ textAlign: "center", maxWidth: 240 }}
        >
          We're tailoring the next steps to you.
        </div>
      </div>
    </Shell>
  );
}

function Income({ ctx }) {
  return (
    <Shell
      title="Your employment"
      progress={ctx.progress}
      footer={
        <button className="btn btn-primary" onClick={ctx.next}>
          Continue <Ic.arrow />
        </button>
      }
    >
      <div className="scr-h1">Tell us about your income</div>
      <div className="scr-lede">
        This helps us set the right limits and see what you qualify for.
      </div>
      <div
        style={{
          display: "flex",
          flexDirection: "column",
          gap: 10,
          marginTop: 4,
        }}
      >
        <div className="field">
          <label>Employment status</label>
          <div className="input filled">Employed — full-time</div>
        </div>
        <div className="field">
          <label>Employer</label>
          <div className="input filled">Maputo Logistics, Lda</div>
        </div>
        <div className="field">
          <label>Monthly income</label>
          <div className="input filled">45,000 MT</div>
        </div>
      </div>
    </Shell>
  );
}

function ProofAddress({ ctx }) {
  return (
    <Shell
      title="Proof of address"
      progress={ctx.progress}
      footer={
        <button className="btn btn-primary" onClick={ctx.next}>
          Continue <Ic.arrow />
        </button>
      }
    >
      <div className="warm-banner">
        <span className="ic">💡</span>
        <span>
          Just a quick extra step — we need to confirm where you live. A utility
          bill or bank statement from the last 3 months works.
        </span>
      </div>
      <div className="scr-h2">Upload a document</div>
      <button
        className="choice"
        style={{ alignItems: "center", flexDirection: "row", gap: 12 }}
      >
        <div className="ic">
          <Ic.upload />
        </div>
        <div style={{ flex: 1 }}>
          <div className="ch-title" style={{ fontSize: 14 }}>
            Utility bill · EDM.pdf
          </div>
          <div className="ch-sub">Uploaded · Mar 2026</div>
        </div>
        <div style={{ color: "var(--green)" }}>
          <Ic.check />
        </div>
      </button>
      <div className="field">
        <label>Residential address</label>
        <div className="input filled">Av. Julius Nyerere 321, Maputo</div>
      </div>
    </Shell>
  );
}

function SourceOfFunds({ ctx }) {
  const [sel, setSel] = useState(["salary"]);
  const opts = [
    { k: "salary", label: "Salary / wages" },
    { k: "business", label: "Business income" },
    { k: "investments", label: "Investments" },
    { k: "inheritance", label: "Inheritance or gift" },
    { k: "property", label: "Property sale" },
    { k: "other", label: "Other" },
  ];
  return (
    <Shell
      title="Source of funds"
      progress={ctx.progress}
      footer={
        <button className="btn btn-primary" onClick={ctx.next}>
          Continue <Ic.arrow />
        </button>
      }
    >
      <div className="warm-banner">
        <span className="ic">🤝</span>
        <span>
          Just a few more details to meet compliance requirements. Your
          information stays private.
        </span>
      </div>
      <div className="scr-h2">Where does your money come from?</div>
      <div className="sof-list">
        {opts.map((o) => (
          <div
            key={o.k}
            className={"sof-item" + (sel.includes(o.k) ? " on" : "")}
            onClick={() =>
              setSel(
                sel.includes(o.k)
                  ? sel.filter((x) => x !== o.k)
                  : [...sel, o.k],
              )
            }
          >
            <span>{o.label}</span>
            {sel.includes(o.k) && <Ic.check />}
          </div>
        ))}
      </div>
    </Shell>
  );
}

function Edd({ ctx }) {
  return (
    <Shell
      title="A few more questions"
      progress={ctx.progress}
      footer={
        <button className="btn btn-primary" onClick={ctx.next}>
          Submit <Ic.arrow />
        </button>
      }
    >
      <div className="warm-banner">
        <span className="ic">🤝</span>
        <span>
          Last set of questions — these help us meet international compliance.
        </span>
      </div>
      <div className="edd-q">
        <div className="q">Purpose of account</div>
        <div className="a">Personal savings & day-to-day banking</div>
      </div>
      <div className="edd-q">
        <div className="q">Expected monthly transactions</div>
        <div className="a">60,000 MT – 120,000 MT</div>
      </div>
      <div className="edd-q">
        <div className="q">Related PEPs (family / associates)</div>
        <div className="a">Spouse — Provincial Assembly member</div>
      </div>
      <div className="edd-q">
        <div className="q">Public role</div>
        <div className="a">
          Advisor to Municipal Council, Maputo · 2024–present
        </div>
      </div>
    </Shell>
  );
}

const ENTITY_CARDS = [
  {
    value: "EI",
    title: "EI",
    sub: "Empresário Individual — sole trader",
    icon: "👤",
  },
  {
    value: "Lda.",
    title: "Lda.",
    sub: "Sociedade por Quotas — most common",
    icon: "🏢",
  },
  {
    value: "EIRL",
    title: "EIRL",
    sub: "Single-member limited liability",
    icon: "🔒",
  },
  {
    value: "SA",
    title: "SA",
    sub: "Sociedade Anónima — joint-stock",
    icon: "🏛",
  },
  {
    value: "Associação",
    title: "Associação",
    sub: "Includes ONGs, cooperatives, non-profit",
    icon: "🤝",
  },
  {
    value: "Outro",
    title: "Outro",
    sub: "Other legal form",
    icon: "…",
  },
];

function BusinessEntityType({ ctx }) {
  const value = ctx.businessEntityType || "";
  const sig = ctx.businessSignatories || "";
  const canContinue = !!value && !!sig;
  return (
    <Shell
      title="Your business"
      progress={ctx.progress}
      footer={
        <button
          className="btn btn-primary"
          onClick={ctx.next}
          disabled={!canContinue}
        >
          Continue <Ic.arrow />
        </button>
      }
    >
      <div className="scr-h1">What's your business's legal form?</div>
      <div className="scr-lede">
        A couple of quick basics about your entity.
      </div>

      <div
        style={{
          fontSize: 10,
          color: "var(--ink-3)",
          letterSpacing: 0.06,
          textTransform: "uppercase",
          marginTop: 4,
        }}
      >
        Signatories
      </div>
      <div
        style={{
          display: "grid",
          gridTemplateColumns: "1fr 1fr",
          gap: 8,
        }}
      >
        {[
          { value: "one", title: "One", sub: "Just me" },
          { value: "many", title: "More than one", sub: "" },
        ].map((o) => {
          const selected = o.value === sig;
          return (
            <button
              key={o.value}
              className={"choice" + (selected ? " selected" : "")}
              onClick={() => ctx.setCtx({ businessSignatories: o.value })}
              style={{ alignItems: "center", textAlign: "center" }}
            >
              <div className="ch-title" style={{ fontSize: 13 }}>
                {o.title}
              </div>
              {o.sub && <div className="ch-sub">{o.sub}</div>}
            </button>
          );
        })}
      </div>

      <div
        style={{
          fontSize: 10,
          color: "var(--ink-3)",
          letterSpacing: 0.06,
          textTransform: "uppercase",
          marginTop: 10,
        }}
      >
        Legal form
      </div>
      <div
        style={{
          display: "flex",
          flexDirection: "column",
          gap: 8,
        }}
      >
        {ENTITY_CARDS.map((c) => {
          const selected = c.value === value;
          return (
            <button
              key={c.value}
              className={"choice" + (selected ? " selected" : "")}
              onClick={() => ctx.setCtx({ businessEntityType: c.value })}
              style={{
                flexDirection: "row",
                alignItems: "center",
                gap: 12,
              }}
            >
              <div
                className="ic"
                style={{ fontSize: 18, lineHeight: 1 }}
                aria-hidden="true"
              >
                {c.icon}
              </div>
              <div style={{ flex: 1, minWidth: 0, textAlign: "left" }}>
                <div className="ch-title" style={{ fontSize: 14 }}>
                  {c.title}
                </div>
                <div className="ch-sub">{c.sub}</div>
              </div>
              {selected && <Ic.check />}
            </button>
          );
        })}
      </div>
    </Shell>
  );
}

function BusinessDetails({ ctx }) {
  return (
    <Shell
      title="About your business"
      progress={ctx.progress}
      footer={
        <button className="btn btn-primary" onClick={ctx.next}>
          Continue <Ic.arrow />
        </button>
      }
    >
      <AboutChip who="business" />
      <div className="scr-h1">Your business</div>
      <div className="scr-lede">
        Quick basics so we can set up your Business Lite account.
      </div>
      <div
        style={{
          display: "flex",
          flexDirection: "column",
          gap: 10,
          marginTop: 4,
        }}
      >
        <div className="field">
          <label>Business name</label>
          <div className="input filled">Magaia & Filhos, Lda</div>
        </div>
        <div className="field">
          <label>Business type</label>
          <div className="input filled">Retail · Food & groceries</div>
        </div>
        <div className="field">
          <label>Business NUIT</label>
          <div className="input filled">401 229 846</div>
        </div>
        <div className="field">
          <label>Expected monthly turnover</label>
          <div className="input filled">250,000 – 500,000 MT</div>
        </div>
      </div>
    </Shell>
  );
}

// Decisioning screens (phone-side). The engine visual lives in backstage; on the phone we keep it minimal.
function Decisioning({ ctx, label = "Checking your application" }) {
  return (
    <Shell
      title="Almost there"
      progress={ctx.progress}
      footer={
        <button className="btn btn-primary" onClick={ctx.next}>
          Continue <Ic.arrow />
        </button>
      }
    >
      <div className="decisioning">
        <div className="spinner" />
        <div className="scr-h2" style={{ textAlign: "center" }}>
          {label}
        </div>
        <div className="scr-lede" style={{ textAlign: "center" }}>
          This only takes a moment.
        </div>
      </div>
    </Shell>
  );
}
function DecisioningLow(p) {
  return <Decisioning {...p} label="All looks good — finalising" />;
}
function DecisioningMedium(p) {
  return (
    <Shell
      title="One more step"
      progress={p.ctx.progress}
      footer={
        <button className="btn btn-primary" onClick={p.ctx.next}>
          Continue <Ic.arrow />
        </button>
      }
    >
      <div className="warm-banner">
        <span className="ic">📄</span>
        <span>
          We need one more document from you to finish opening your account —
          proof of your address.
        </span>
      </div>
      <div className="scr-h1">Nearly there</div>
      <div className="scr-lede">
        This is a standard check. Upload a recent utility bill or statement and
        we'll be done.
      </div>
    </Shell>
  );
}
function DecisioningPep(p) {
  return (
    <Shell
      title="A few more details"
      progress={p.ctx.progress}
      footer={
        <button className="btn btn-primary" onClick={p.ctx.next}>
          Continue <Ic.arrow />
        </button>
      }
    >
      <div className="warm-banner">
        <span className="ic">🤝</span>
        <span>
          Because of your role, we need to ask a few additional questions. We'll
          guide you through each one.
        </span>
      </div>
      <div className="scr-h1">Just a few more details</div>
      <div className="scr-lede">
        This takes about 3 minutes. You can save and continue later if you need
        to.
      </div>
    </Shell>
  );
}
function DecisioningFinal(p) {
  return <Decisioning {...p} label="Final check — looks great" />;
}
function DecisioningFinalPep(p) {
  return (
    <Shell
      title="Under review"
      progress={p.ctx.progress}
      footer={
        <button className="btn btn-primary" onClick={p.ctx.next}>
          See next steps <Ic.arrow />
        </button>
      }
    >
      <div className="decisioning">
        <div
          style={{
            width: 56,
            height: 56,
            borderRadius: 28,
            background: "var(--amber-soft)",
            color: "#8A5A10",
            display: "grid",
            placeItems: "center",
            fontSize: 28,
          }}
        >
          📋
        </div>
        <div className="scr-h2" style={{ textAlign: "center" }}>
          Thanks — you're all done
        </div>
        <div
          className="scr-lede"
          style={{ textAlign: "center", maxWidth: 280 }}
        >
          We'll review your application within 1 business day and message you
          when your account is ready. Your channel preferences and card are
          queued — we'll activate them once review clears.
        </div>
      </div>
    </Shell>
  );
}

function AccountCreated({ ctx }) {
  const isWallet = ctx.journey.key === "wallet";
  return (
    <Shell
      title={isWallet ? "Wallet ready" : "You're in"}
      progress={ctx.progress}
      footer={
        <button className="btn btn-primary" onClick={ctx.next}>
          {isWallet ? "Set up your wallet" : "Set up your account"} <Ic.arrow />
        </button>
      }
    >
      <div
        style={{
          flex: 1,
          display: "flex",
          flexDirection: "column",
          alignItems: "center",
          justifyContent: "center",
          gap: 14,
        }}
      >
        <div className="success-circle">
          <span className="big-check">✓</span>
        </div>
        <div className="scr-h1" style={{ textAlign: "center" }}>
          Welcome, Dércia
        </div>
        <div
          className="scr-lede"
          style={{ textAlign: "center", maxWidth: 260 }}
        >
          {isWallet
            ? "Your wallet is created. Just a couple more things to get you transacting."
            : "Your account is created. Just a couple more things to get you transacting."}
        </div>
      </div>
    </Shell>
  );
}
function AccountCreatedSme({ ctx }) {
  return (
    <Shell
      title="Business account created"
      progress={ctx.progress}
      footer={
        <button className="btn btn-primary" onClick={ctx.next}>
          Set it up <Ic.arrow />
        </button>
      }
    >
      <div
        style={{
          flex: 1,
          display: "flex",
          flexDirection: "column",
          alignItems: "center",
          justifyContent: "center",
          gap: 14,
        }}
      >
        <div className="success-circle">
          <span className="big-check">✓</span>
        </div>
        <div className="scr-h1" style={{ textAlign: "center" }}>
          Magaia & Filhos
        </div>
        <div
          className="scr-lede"
          style={{ textAlign: "center", maxWidth: 260 }}
        >
          Your business account is ready to be set up for transactions.
        </div>
      </div>
    </Shell>
  );
}

function ChoiceRow({ selected, dimmed, icon, title, sub, onClick }) {
  return (
    <button
      className={"choice" + (selected ? " selected" : "")}
      onClick={onClick}
      disabled={!!dimmed}
      style={{
        flexDirection: "row",
        alignItems: "center",
        gap: 12,
        opacity: dimmed ? 0.55 : 1,
        cursor: dimmed ? "not-allowed" : "pointer",
      }}
    >
      <div className="ic">{icon}</div>
      <div style={{ flex: 1 }}>
        <div className="ch-title" style={{ fontSize: 14 }}>
          {title}
        </div>
        <div className="ch-sub">{sub}</div>
      </div>
      {selected && <Ic.check />}
    </button>
  );
}

function BranchPicker({ pickupBranch, setBranch }) {
  const [open, setOpen] = useState(false);
  const branches = ["Sede", "Baixa", "Matola", "Beira"];
  if (!open) {
    return (
      <div
        style={{
          display: "inline-flex",
          alignItems: "center",
          gap: 6,
          padding: "5px 11px",
          background: "var(--line-2)",
          borderRadius: 999,
          color: "var(--ink-2)",
          fontSize: 11,
          marginTop: 2,
          marginLeft: 4,
          alignSelf: "flex-start",
        }}
      >
        <span>📍 Pickup at</span>
        <strong style={{ color: "var(--ink)", fontWeight: 600 }}>
          {pickupBranch}
        </strong>
        <button
          onClick={() => setOpen(true)}
          style={{
            background: "none",
            border: "none",
            padding: 0,
            margin: "0 0 0 4px",
            color: "var(--teal)",
            fontWeight: 600,
            cursor: "pointer",
            fontSize: 11,
          }}
        >
          Change
        </button>
      </div>
    );
  }
  return (
    <div
      style={{
        display: "flex",
        flexDirection: "column",
        gap: 4,
        marginTop: 2,
        marginLeft: 4,
      }}
    >
      <div
        style={{
          fontSize: 10,
          color: "var(--ink-3)",
          textTransform: "uppercase",
          letterSpacing: "0.06em",
          marginBottom: 2,
        }}
      >
        Pickup branch
      </div>
      {branches.map((b) => (
        <button
          key={b}
          onClick={() => {
            setBranch(b);
            setOpen(false);
          }}
          style={{
            padding: "7px 11px",
            borderRadius: 8,
            background: b === pickupBranch ? "rgba(0,128,128,0.08)" : "#fff",
            border: `1px solid ${b === pickupBranch ? "var(--teal)" : "var(--line)"}`,
            color: "var(--ink)",
            textAlign: "left",
            fontSize: 12,
            cursor: "pointer",
            fontWeight: b === pickupBranch ? 600 : 500,
          }}
        >
          📍 {b}
        </button>
      ))}
    </div>
  );
}

function TxSetupDigital({ ctx }) {
  const ussdReady = ctx.opsState === "target";
  return (
    <Shell
      title="How you'll transact"
      progress={ctx.progress}
      footer={
        <button className="btn btn-primary" onClick={ctx.next}>
          Continue <Ic.arrow />
        </button>
      }
    >
      <div className="scr-h1">Set up digital access</div>
      <div className="scr-lede">
        Send, receive, and pay straight from your phone. A card can be added
        later.
      </div>
      <ChoiceRow
        selected={ussdReady}
        dimmed={!ussdReady}
        icon="📞"
        title="USSD banking"
        sub={ussdReady ? "Dial *123# · Ready immediately" : "Coming soon"}
      />
      <ChoiceRow
        selected
        icon="💻"
        title="Digital banking"
        sub="Web + mobile · Ready immediately"
      />
      <div style={{ fontSize: 11, color: "var(--ink-3)", marginTop: 4 }}>
        Debit card not available on Wallet. Upgrade anytime.
      </div>
    </Shell>
  );
}

function TxSetupCard({ ctx }) {
  const cardChoice = ctx.cardChoice || "instant";
  const pickupBranch = ctx.pickupBranch || "Sede";
  const setCard = (v) => ctx.setCtx({ cardChoice: v });
  const setBranch = (b) => ctx.setCtx({ pickupBranch: b });
  const ussdReady = ctx.opsState === "target";
  return (
    <Shell
      title="How you'll transact"
      progress={ctx.progress}
      footer={
        <button className="btn btn-primary" onClick={ctx.next}>
          Continue <Ic.arrow />
        </button>
      }
    >
      <div className="scr-h1">Pick your channels</div>
      <div className="scr-lede">You can pick multiple — most customers do.</div>
      <ChoiceRow
        selected={ussdReady}
        dimmed={!ussdReady}
        icon="📞"
        title="USSD banking"
        sub={ussdReady ? "Dial *123# · Ready immediately" : "Coming soon"}
      />
      <ChoiceRow
        selected
        icon="💻"
        title="Digital banking"
        sub="Web + mobile · Ready immediately"
      />
      <ChoiceRow
        selected={cardChoice === "instant"}
        icon="💳"
        title="Instant debit card"
        sub="Generic · pick up at branch today"
        onClick={() => setCard("instant")}
      />
      {cardChoice === "instant" && (
        <BranchPicker pickupBranch={pickupBranch} setBranch={setBranch} />
      )}
      <ChoiceRow
        selected={cardChoice === "personalized"}
        icon="💳"
        title="Personalized debit card"
        sub="Your name on the card · 1–3 business days"
        onClick={() => setCard("personalized")}
      />
      {cardChoice === "personalized" && (
        <BranchPicker pickupBranch={pickupBranch} setBranch={setBranch} />
      )}
    </Shell>
  );
}

function TxSetupSme({ ctx }) {
  const cardChoice = ctx.cardChoice || "instant";
  const pickupBranch = ctx.pickupBranch || "Sede";
  const setCard = (v) => ctx.setCtx({ cardChoice: v });
  const setBranch = (b) => ctx.setCtx({ pickupBranch: b });
  return (
    <Shell
      title="Business transacting"
      progress={ctx.progress}
      footer={
        <button className="btn btn-primary" onClick={ctx.next}>
          Continue <Ic.arrow />
        </button>
      }
    >
      <div className="scr-h1">How your business will transact</div>
      <div className="scr-lede">
        You can pick multiple — most businesses do.
      </div>
      <ChoiceRow
        selected
        icon="💻"
        title="Digital banking"
        sub="Web + mobile · Ready immediately"
      />
      <ChoiceRow
        selected={cardChoice === "instant"}
        icon="💳"
        title="Instant business debit card"
        sub="Generic · pick up at branch today"
        onClick={() => setCard("instant")}
      />
      {cardChoice === "instant" && (
        <BranchPicker pickupBranch={pickupBranch} setBranch={setBranch} />
      )}
      <ChoiceRow
        selected={cardChoice === "personalized"}
        icon="💳"
        title="Personalized business debit card"
        sub="Your name on the card · 1–3 business days"
        onClick={() => setCard("personalized")}
      />
      {cardChoice === "personalized" && (
        <BranchPicker pickupBranch={pickupBranch} setBranch={setBranch} />
      )}
    </Shell>
  );
}

function Activation({ ctx }) {
  const isTarget = ctx.opsState === "target";
  const jk = ctx.journey.key;
  const cardChoice = ctx.cardChoice || "instant";
  const pickupBranch = ctx.pickupBranch || "Sede";

  const items = [{ label: "Identity verified", k: "id" }];
  if (jk === "standard-medium" || jk === "standard-pep") {
    items.push({ label: "Documents verified", k: "docs" });
  } else if (jk === "sme") {
    items.push({ label: "Business documents verified", k: "docs" });
  }
  items.push({
    label: jk === "wallet" ? "Wallet ready" : "Account ready",
    k: "account",
  });
  if (isTarget) {
    items.push({ label: "USSD banking activated", k: "ussd" });
    items.push({ label: "Digital banking activated", k: "digital" });
  } else {
    items.push({ label: "Digital access activated", k: "digital" });
  }
  if (jk !== "wallet" && jk !== "entry") {
    items.push({
      label:
        cardChoice === "instant"
          ? "Card ready for branch pickup"
          : "Card in production",
      k: "card",
    });
  }

  const accountIdx = items.findIndex((x) => x.k === "account");
  const docsIdx = items.findIndex((x) => x.k === "docs");
  const cardIdx = items.findIndex((x) => x.k === "card");

  const marks = items.map((it) => {
    if (it.k === "id") return true;
    if (it.k === "docs") return isTarget;
    if (it.k === "ussd" || it.k === "digital") return isTarget;
    if (it.k === "account" || it.k === "card") return false;
    return isTarget;
  });

  const accountDone = marks[0] && (docsIdx < 0 || marks[docsIdx]);
  marks[accountIdx] = accountDone;
  if (cardIdx >= 0) {
    marks[cardIdx] = accountDone && cardChoice === "instant";
  }

  const allDone = marks.every(Boolean);

  return (
    <Shell
      title="Setting up your account"
      progress={ctx.progress}
      footer={
        <button
          className="btn btn-primary"
          onClick={ctx.next}
          disabled={!accountDone}
        >
          {accountDone ? (
            <>
              Add money <Ic.arrow />
            </>
          ) : (
            "We'll notify you when ready"
          )}
        </button>
      }
    >
      <div className="scr-h1">
        {allDone
          ? jk === "wallet"
            ? "Your wallet is ready"
            : "Your account is ready"
          : accountDone
            ? jk === "wallet"
              ? "Your wallet is ready — add money anytime"
              : "Your account is ready — add money anytime"
            : "Almost there"}
      </div>
      <div className="scr-lede">
        {allDone
          ? "Everything's set up. Add your first money to get going."
          : accountDone
            ? "You can start adding money now. We'll finish a few things in the background."
            : "We're finishing a couple of things in the background. You can close the app — we'll message you when it's ready."}
      </div>
      <div className="checklist">
        {items.map((i, idx) => {
          const done = marks[idx];
          return (
            <div key={idx} className={"chk-item" + (done ? " done" : "")}>
              <div className="chk-icon">
                {done ? <Ic.check /> : <span className="spin-sm" />}
              </div>
              <span>{i.label}</span>
            </div>
          );
        })}
      </div>
      {accountDone && (
        <div className="details-card">
          {jk === "wallet" ? (
            <div className="dline">
              <span className="k">Wallet number</span>
              <span className="v">+258841234567</span>
            </div>
          ) : (
            <>
              <div className="dline">
                <span className="k">Account number</span>
                <span className="v">00482911740</span>
              </div>
              <div className="dline">
                <span className="k">NIB</span>
                <span className="v">000800000482911740123</span>
              </div>
              <div className="dline">
                <span className="k">SWIFT / BIC</span>
                <span className="v">FINDMZMA</span>
              </div>
            </>
          )}
          {items.some((i) => i.k === "card") && (
            <div className="dline">
              <span className="k">Card pickup</span>
              <span className="v">{pickupBranch}</span>
            </div>
          )}
        </div>
      )}
    </Shell>
  );
}

function FundRow({ featured, icon, title, sub, dimmed }) {
  return (
    <button
      className={"fund-row" + (featured ? " featured" : "")}
      disabled={!!dimmed}
      style={dimmed ? { opacity: 0.55, cursor: "not-allowed" } : undefined}
    >
      <div className="fico">{icon}</div>
      <div className="fbody">
        <div className="ftitle">{title}</div>
        <div className="fsub">{sub}</div>
      </div>
      <div className="chev">
        <Ic.chev />
      </div>
    </button>
  );
}

function FirstFunding({ ctx }) {
  const agentSoon = ctx.opsState === "initial";
  return (
    <Shell title="Add money" progress={100} footer={null}>
      <div className="scr-h1">What would you like to do next?</div>
      <div className="scr-lede">
        Start small — move 100 MT and see how fast it lands.
      </div>
      <div className="fund-stack">
        <FundRow
          featured
          icon="📥"
          title="Receive money"
          sub="Share your account details or QR code"
        />
        <FundRow
          featured
          icon="📲"
          title="Transfer from M-Pesa / Emola"
          sub="From your mobile wallet, in seconds"
        />
        <FundRow
          icon="🧑‍💼"
          title="Agent deposit"
          sub={agentSoon ? "Coming soon" : "Find a bank agent nearby"}
          dimmed={agentSoon}
        />
        <FundRow icon="🏦" title="Bank transfer" sub="From another bank" />
        <FundRow icon="🏛️" title="Branch deposit" sub="Cash at branch" />
      </div>
      <div className="fund-skip">Skip for now</div>
    </Shell>
  );
}

function FirstFundingSme({ ctx }) {
  const agentSoon = ctx.opsState === "initial";
  return (
    <Shell title="Fund your business" progress={100} footer={null}>
      <div className="scr-h1">How will you fund your business?</div>
      <div className="scr-lede">
        Get started by moving some opening capital or accepting your first
        payment.
      </div>
      <div className="fund-stack">
        <FundRow
          featured
          icon="📥"
          title="Receive from a customer"
          sub="Share invoice or QR code"
        />
        <FundRow
          featured
          icon="🏦"
          title="Bank transfer"
          sub="From another bank account"
        />
        <FundRow icon="📲" title="M-Pesa / Emola" sub="From a mobile wallet" />
        <FundRow
          icon="🧑‍💼"
          title="Agent deposit"
          sub={agentSoon ? "Coming soon" : "Find a bank agent nearby"}
          dimmed={agentSoon}
        />
        <FundRow icon="🏛️" title="Branch deposit" sub="Cash at branch" />
      </div>
      <div className="fund-skip">Skip for now</div>
    </Shell>
  );
}

// SME required business documents
function BusinessDocsRequired({ ctx }) {
  return (
    <Shell
      title="Required business documents"
      progress={ctx.progress}
      footer={
        <button className="btn btn-primary" onClick={ctx.next}>
          Continue <Ic.arrow />
        </button>
      }
    >
      <AboutChip who="business" />
      <div className="scr-h1">Required documents</div>
      <div className="scr-lede">
        We need these to open your business account. Upload a photo or PDF.
      </div>
      <button
        className="choice"
        style={{ alignItems: "center", flexDirection: "row", gap: 12 }}
      >
        <div className="ic">
          <Ic.upload />
        </div>
        <div style={{ flex: 1 }}>
          <div className="ch-title" style={{ fontSize: 14 }}>
            Alvará
          </div>
          <div className="ch-sub">Operating licence · uploaded</div>
        </div>
        <div style={{ color: "var(--green)" }}>
          <Ic.check />
        </div>
      </button>
      <button
        className="choice"
        style={{ alignItems: "center", flexDirection: "row", gap: 12 }}
      >
        <div className="ic">
          <Ic.upload />
        </div>
        <div style={{ flex: 1 }}>
          <div className="ch-title" style={{ fontSize: 14 }}>
            Certidão Comercial
          </div>
          <div className="ch-sub">Commercial registration · uploaded</div>
        </div>
        <div style={{ color: "var(--green)" }}>
          <Ic.check />
        </div>
      </button>
    </Shell>
  );
}

function BusinessDocsSupporting({ ctx }) {
  return (
    <Shell
      title="Supporting documents"
      progress={ctx.progress}
      footer={
        <button className="btn btn-primary" onClick={ctx.next}>
          Continue <Ic.arrow />
        </button>
      }
    >
      <AboutChip who="business" />
      <div className="scr-h1">Supporting documents</div>
      <div className="scr-lede">A couple more to complete your profile.</div>
      <button
        className="choice"
        style={{ alignItems: "center", flexDirection: "row", gap: 12 }}
      >
        <div className="ic">
          <Ic.upload />
        </div>
        <div style={{ flex: 1 }}>
          <div className="ch-title" style={{ fontSize: 14 }}>
            Modelo 11
          </div>
          <div className="ch-sub">Tax registration · uploaded</div>
        </div>
        <div style={{ color: "var(--green)" }}>
          <Ic.check />
        </div>
      </button>
      <button
        className="choice"
        style={{ alignItems: "center", flexDirection: "row", gap: 12 }}
      >
        <div className="ic">
          <Ic.upload />
        </div>
        <div style={{ flex: 1 }}>
          <div className="ch-title" style={{ fontSize: 14 }}>
            Proof of business address
          </div>
          <div className="ch-sub">Utility bill · uploaded</div>
        </div>
        <div style={{ color: "var(--green)" }}>
          <Ic.check />
        </div>
      </button>
    </Shell>
  );
}

// =========== RESUME ===========

function ResumeVerify({ ctx }) {
  return (
    <Shell
      title="Welcome back"
      progress={ctx.progress}
      footer={
        <button className="btn btn-primary" onClick={ctx.next}>
          Continue <Ic.arrow />
        </button>
      }
    >
      <div className="scr-h1">Pick up where you left off</div>
      <div className="scr-lede">
        Enter your phone number and the code we'll text you. We'll restore your
        saved progress.
      </div>
      <div className="field" style={{ marginTop: 6 }}>
        <label>Phone</label>
        <div className="input filled">+258 84 123 4567</div>
      </div>
      <div className="field">
        <label>Verification code</label>
        <div className="input filled" style={{ letterSpacing: "0.25em" }}>
          4 8 2 9 1 7{" "}
          <span
            style={{ color: "var(--green)", letterSpacing: 0, marginLeft: 8 }}
          >
            <Ic.check />
          </span>
        </div>
      </div>
    </Shell>
  );
}

function ResumeStatus({ ctx }) {
  const done = [
    "Identity verified",
    "ID captured",
    "Liveness complete",
    "NUIT on file",
  ];
  const upNext = "Income & employment";
  const upcoming = ["Account ready"];
  return (
    <Shell
      title="Welcome back"
      progress={ctx.progress}
      footer={
        <button className="btn btn-primary" onClick={ctx.next}>
          Continue where you left off <Ic.arrow />
        </button>
      }
    >
      <div className="scr-h1">Welcome back, Dércia</div>
      <div className="scr-lede">
        We've saved your progress. Pick up where you left off, or tap a
        completed step to review.
      </div>
      <div style={{ fontSize: 11, color: "var(--ink-3)", marginTop: 2 }}>
        Started 2 days ago
      </div>

      <div className="checklist" style={{ marginTop: 6 }}>
        {done.map((label, i) => (
          <button
            key={"d" + i}
            type="button"
            className="chk-item done resume-review"
          >
            <div className="chk-icon">
              <Ic.check />
            </div>
            <span style={{ flex: 1, textAlign: "left" }}>{label}</span>
            <span className="resume-review-tag">Review</span>
          </button>
        ))}
      </div>

      <div className="upnext-card">
        <div className="upnext-label">Up next</div>
        <div className="upnext-title">{upNext}</div>
        <div className="upnext-sub">Tap continue below to pick up here.</div>
      </div>

      <div className="checklist" style={{ marginTop: 4, opacity: 0.55 }}>
        {upcoming.map((label, i) => (
          <div key={"p" + i} className="chk-item">
            <div className="chk-icon">
              <span className="spin-sm" />
            </div>
            <span>{label}</span>
          </div>
        ))}
      </div>

      <div
        style={{
          fontSize: 11,
          color: "var(--ink-3)",
          marginTop: "auto",
          paddingTop: 6,
        }}
      >
        Tap any completed step to review or edit.
      </div>
    </Shell>
  );
}

const SCREENS = {
  EntryType,
  EntryIntents,
  EntryReco,
  EntryOptions,
  BusinessEntityType,
  Consent,
  Signature,
  Identity,
  IdentityDetails,
  IdCapture,
  Liveness,
  Nuit,
  Income,
  ProofAddress,
  SourceOfFunds,
  Edd,
  BusinessDetails,
  BusinessDocsRequired,
  BusinessDocsSupporting,
  RiskScoring,
  Decisioning,
  DecisioningLow,
  DecisioningMedium,
  DecisioningPep,
  DecisioningFinal,
  DecisioningFinalPep,
  AccountCreated,
  AccountCreatedSme,
  TxSetupDigital,
  TxSetupCard,
  TxSetupSme,
  Activation,
  FirstFunding,
  FirstFundingSme,
  ResumeVerify,
  ResumeStatus,
};

Object.assign(window, { SCREENS, Ic });
