// ============================================================
// Warm flow + shared screens
// Screens (in order): Offer → Amount → Plaid → Business → Owner
//   → Review → Decision → Agreement → Funded → Dashboard
// Cold flow reuses Plaid, Business, Owner, Review, Agreement, Funded.
// ============================================================

const fmtUSD = (n) => "$" + Math.round(n).toLocaleString();
const computeTerms = (draw, factor) => {
  const payback = draw * factor;
  // Weekly payment sized so payback delivers in roughly 50 weeks (~12 months).
  const weekly = Math.round(payback / 50 / 50) * 50; // round to nearest $50
  const weeks = Math.max(1, Math.round(payback / weekly));
  const months = Math.round(weeks / 4.3);
  // Daily kept for legal-text contexts only.
  const daily = Math.round(weekly / 5);
  return { payback, weekly, weeks, months, daily };
};

// =====================================================================
// 1) PRE-QUALIFIED OFFER (warm only)
// =====================================================================
const ScreenOffer = ({ tweaks, ownerName, onContinue, onBack }) => {
  const { offerAmount, partnerName } = tweaks;
  return (
    <div className="cap fade-up">
      <div className="cap-shell">
        <div className="cap-header">
          <CapitalCobrand partnerName={partnerName} attribution={tweaks.revenuedAttribution} />
          <button className="btn btn-text" onClick={onBack} style={{ alignSelf: "flex-end" }}>
            <Icon name="x" size={14} /> Close
          </button>
        </div>

        <div>
          {/* Hero offer */}
          <div className="card card-pad" style={{
            background: "linear-gradient(135deg, var(--growth-galaxy) 0%, var(--trust-tech) 100%)",
            color: "#fff", position: "relative", overflow: "hidden", borderRadius: 20, border: "none",
            padding: "44px 48px"
          }}>
            {/* Ambient ring on the far left */}
            <div style={{ position: "absolute", left: -180, bottom: -180, opacity: 0.45, pointerEvents: "none" }}>
              <Rings size={460} palette="teal" />
            </div>

            <div style={{
              position: "relative", zIndex: 1,
              display: "grid", gridTemplateColumns: "minmax(0, 1fr) minmax(0, 1fr)",
              gap: 56, alignItems: "center"
            }}>
              {/* LEFT — narrative + CTA */}
              <div>
                <div style={{
                  display: "inline-flex", alignItems: "center", gap: 8,
                  padding: "5px 11px 5px 9px",
                  background: "rgba(4,196,158,0.14)",
                  border: "1px solid rgba(4,196,158,0.32)",
                  borderRadius: 999,
                  fontSize: 11, fontWeight: 700, letterSpacing: "0.12em",
                  textTransform: "uppercase", color: "var(--funding-pool)",
                  marginBottom: 22
                }}>
                  <Icon name="badge-check" size={13} color="var(--funding-pool)" />
                  Pre-Qualified Offer
                </div>

                <h1 style={{
                  fontFamily: "var(--font-primary)", fontWeight: 700,
                  fontSize: 44, lineHeight: 1.05, letterSpacing: "-0.025em",
                  margin: "0 0 16px"
                }}>
                  Hi {ownerName.split(" ")[0]} — your Flex Line is ready when you are.
                </h1>
                <p style={{
                  fontSize: 16.5, color: "rgba(255,255,255,0.78)",
                  lineHeight: 1.55, maxWidth: 460, margin: "0 0 28px"
                }}>
                  Based on your {partnerName} sales, you can take what you need today and pull more later — all on one line.
                </p>

                <div style={{ display: "flex", flexWrap: "wrap", gap: 8, marginBottom: 32 }}>
                  {[
                    { ic: "shield-check", t: "Soft credit pull only" },
                    { ic: "zap", t: "Funds in 24 hours" },
                    { ic: "circle-dollar-sign", t: "No application fees" }].
                    map((p, i) =>
                      <div key={i} style={{
                        display: "flex", alignItems: "center", gap: 7,
                        fontSize: 12, fontWeight: 500, color: "rgba(255,255,255,0.85)",
                        padding: "7px 12px",
                        background: "rgba(255,255,255,0.08)",
                        borderRadius: 999, border: "1px solid rgba(255,255,255,0.10)"
                      }}>
                        <Icon name={p.ic} size={13} color="var(--funding-pool)" />
                        {p.t}
                      </div>
                    )}
                </div>

                <button onClick={onContinue} className="btn btn-teal btn-lg" style={{ minWidth: 240 }}>
                  Check My Eligibility <Icon name="arrow-right" size={16} />
                </button>
              </div>

              {/* RIGHT — the showpiece amount */}
              <div style={{
                position: "relative",
                display: "grid", placeItems: "center",
                minHeight: 360
              }}>
                {/* Offset ring ornaments — wreath the composition without crossing the number */}
                <div style={{ position: "absolute", right: -70, top: -50, opacity: 0.55, pointerEvents: "none" }}>
                  <Rings size={300} palette="teal" />
                </div>
                <div style={{ position: "absolute", left: -50, bottom: -40, opacity: 0.32, pointerEvents: "none" }}>
                  <Rings size={220} palette="teal" />
                </div>

                {/* Darker stage disc — gives the number a clean canvas */}
                <div style={{
                  position: "absolute",
                  width: 460, height: 280,
                  borderRadius: "50%",
                  background: "radial-gradient(ellipse at center, rgba(0,18,43,0.55) 0%, rgba(0,18,43,0.25) 45%, rgba(0,18,43,0) 75%)",
                  pointerEvents: "none"
                }} />
                {/* Subtle teal glow on top of the stage */}
                <div style={{
                  position: "absolute",
                  width: 320, height: 320, borderRadius: "50%",
                  background: "radial-gradient(circle at center, rgba(4,196,158,0.22) 0%, rgba(4,196,158,0) 60%)",
                  pointerEvents: "none"
                }} />

                <div style={{ position: "relative", textAlign: "center" }}>
                  <div style={{
                    fontSize: 11, fontWeight: 700, letterSpacing: "0.18em",
                    textTransform: "uppercase",
                    color: "rgba(255,255,255,0.7)",
                    marginBottom: 14
                  }}>
                    You're pre-qualified up to
                  </div>
                  <div style={{
                    fontFamily: "var(--font-primary)", fontWeight: 700,
                    fontSize: "clamp(56px, 8.5vw, 104px)",
                    lineHeight: 0.95, letterSpacing: "-0.035em",
                    fontVariantNumeric: "tabular-nums",
                    whiteSpace: "nowrap",
                    color: "#ffffff",
                    textShadow: "0 2px 24px rgba(0,18,43,0.45)",
                    margin: "0 0 18px"
                  }}>
                    {fmtUSD(offerAmount)}
                  </div>
                  <div style={{
                    display: "inline-flex", alignItems: "center", gap: 10,
                    padding: "8px 16px",
                    background: "rgba(255,255,255,0.10)",
                    border: "1px solid rgba(255,255,255,0.18)",
                    borderRadius: 999,
                    fontSize: 12.5, fontWeight: 500,
                    color: "rgba(255,255,255,0.85)",
                    backdropFilter: "blur(6px)"
                  }}>
                    <Icon name="infinity" size={14} color="var(--funding-pool)" />
                    Reusable line · draw what you need
                  </div>
                </div>
              </div>
            </div>

            {/* Footer disclosure inside the hero */}
            <div style={{
              position: "relative", zIndex: 1,
              marginTop: 36, paddingTop: 18,
              borderTop: "1px solid rgba(255,255,255,0.12)",
              fontSize: 11.5, lineHeight: 1.55,
              color: "rgba(255,255,255,0.6)",
              maxWidth: 720
            }}>
              Revenued's service provides for the purchase of future receivables and is not a loan. Final terms and amount confirmed after a soft credit review.
            </div>
          </div>
        </div>

        {/* How it works */}
        <div className="mt-8" style={{ marginTop: 36 }}>
          <Eyebrow>How it works</Eyebrow>
          <div style={{ display: "grid", gridTemplateColumns: "repeat(3, 1fr)", gap: 16, marginTop: 16 }}>
            {[
              { n: "01", ic: "sliders-horizontal", t: "Choose your amount", d: "Pick anything up to your max. Pull more later as your line refills." },
              { n: "02", ic: "link", t: "Connect your bank", d: "Plaid secure connection. We use it to verify revenue and set up payback." },
              { n: "03", ic: "send", t: "Get funded", d: "Most merchants see funds the next business day. No hidden fees." }].
              map((s, i) =>
                <div key={i} className="card card-pad" style={{ position: "relative" }}>
                  <div style={{
                    fontSize: 11, fontWeight: 700, letterSpacing: "0.12em",
                    color: "var(--tt-40)", fontFamily: "var(--font-mono)"
                  }}>{s.n}</div>
                  <div style={{
                    width: 44, height: 44, borderRadius: 10,
                    background: "var(--gg-5)", color: "var(--growth-galaxy)",
                    display: "grid", placeItems: "center", margin: "16px 0 18px"
                  }}>
                    <Icon name={s.ic} size={22} />
                  </div>
                  <div style={{ fontSize: 16, fontWeight: 700, marginBottom: 8 }}>{s.t}</div>
                  <div style={{ fontSize: 13.5, color: "var(--tt-60)", lineHeight: 1.5 }}>{s.d}</div>
                </div>
              )}
          </div>
        </div>
      </div>
    </div>);

};

// =====================================================================
// 2) AMOUNT SELECTION (warm)
// =====================================================================
const AmountField = ({ value, onChange, min, max }) => {
  const [text, setText] = React.useState(value.toLocaleString());
  React.useEffect(() => { setText(value.toLocaleString()); }, [value]);

  const handleChange = (e) => {
    const raw = e.target.value.replace(/[^0-9]/g, "");
    if (!raw) { setText(""); return; }
    const n = Math.min(max, parseInt(raw, 10));
    setText(n.toLocaleString());
    onChange(n);
  };
  const handleBlur = () => {
    const n = Math.max(min, Math.min(max, value || min));
    onChange(n);
    setText(n.toLocaleString());
  };

  return (
    <div style={{
      display: "inline-flex", alignItems: "baseline", gap: 6,
      padding: "8px 16px 12px",
      borderRadius: 14,
      background: "var(--tt-5)",
      border: "1px solid var(--border-1)",
      transition: "border-color 0.15s, background 0.15s"
    }} className="amount-field">
      <span style={{
        fontFamily: "var(--font-primary)", fontWeight: 600,
        fontSize: 40, lineHeight: 1, color: "var(--tt-40)"
      }}>$</span>
      <input
        value={text}
        onChange={handleChange}
        onBlur={handleBlur}
        inputMode="numeric"
        aria-label="Draw amount"
        style={{
          fontFamily: "var(--font-primary)", fontWeight: 700,
          fontSize: 64, lineHeight: 1, letterSpacing: "-0.025em",
          color: "var(--trust-tech)",
          border: "none", outline: "none", background: "transparent",
          padding: 0, margin: 0,
          width: `${Math.max(text.length, 2) + 0.5}ch`,
          fontVariantNumeric: "tabular-nums"
        }} />

      <style>{`
        .amount-field:focus-within {
          border-color: var(--growth-galaxy);
          background: #fff;
          box-shadow: 0 0 0 4px rgba(0,64,186,0.08);
        }
      `}</style>
    </div>);

};

const FlexLineDial = ({ drawn, total, partnerName }) => {
  const pct = Math.max(0, Math.min(1, drawn / total));
  const r = 78;
  const c = 2 * Math.PI * r;
  const dashed = pct * c;
  return (
    <div style={{ display: "flex", flexDirection: "column", alignItems: "center", gap: 22 }}>
      <div style={{ position: "relative", width: 220, height: 220 }}>
        <svg width="220" height="220" viewBox="0 0 220 220" style={{ display: "block" }}>
          {/* Track */}
          <circle cx="110" cy="110" r={r} fill="none" stroke="var(--gg-10)" strokeWidth="16" />
          {/* Drawn portion */}
          <circle
            cx="110" cy="110" r={r}
            fill="none"
            stroke="var(--growth-galaxy)"
            strokeWidth="16"
            strokeLinecap="round"
            strokeDasharray={`${dashed} ${c}`}
            transform="rotate(-90 110 110)"
            style={{ transition: "stroke-dasharray 0.25s ease-out" }} />

        </svg>
        <div style={{
          position: "absolute", inset: 0,
          display: "flex", flexDirection: "column", alignItems: "center", justifyContent: "center"
        }}>
          <div style={{
            fontSize: 11, fontWeight: 700, letterSpacing: "0.12em",
            color: "var(--tt-60)", textTransform: "uppercase"
          }}>Drawing</div>
          <div className="tnum" style={{
            fontFamily: "var(--font-primary)", fontWeight: 700,
            fontSize: 34, lineHeight: 1.05, letterSpacing: "-0.02em",
            color: "var(--trust-tech)", marginTop: 4
          }}>{Math.round(pct * 100)}%</div>
          <div style={{ fontSize: 11.5, color: "var(--tt-60)", marginTop: 4 }}>
            of your line
          </div>
        </div>
      </div>

      <div style={{ width: "100%", display: "flex", flexDirection: "column", gap: 12 }}>
        <div style={{ display: "flex", alignItems: "center", gap: 10 }}>
          <span style={{ width: 10, height: 10, borderRadius: 3, background: "var(--growth-galaxy)" }} />
          <div style={{ flex: 1, fontSize: 12.5, color: "var(--tt-60)" }}>Drawing now</div>
          <div className="tnum" style={{ fontSize: 13, fontWeight: 700, color: "var(--trust-tech)" }}>{fmtUSD(drawn)}</div>
        </div>
        <div style={{ display: "flex", alignItems: "center", gap: 10 }}>
          <span style={{ width: 10, height: 10, borderRadius: 3, background: "var(--gg-10)", border: "1px solid var(--border-1)" }} />
          <div style={{ flex: 1, fontSize: 12.5, color: "var(--tt-60)" }}>Stays on your line</div>
          <div className="tnum" style={{ fontSize: 13, fontWeight: 700, color: "var(--trust-tech)" }}>{fmtUSD(total - drawn)}</div>
        </div>
        <div style={{ height: 1, background: "var(--border-1)", margin: "2px 0" }} />
        <div style={{ display: "flex", alignItems: "center", gap: 10 }}>
          <div style={{ flex: 1, fontSize: 12, fontWeight: 600, color: "var(--tt-80)" }}>Flex Line · {partnerName}</div>
          <div className="tnum" style={{ fontSize: 13, fontWeight: 700, color: "var(--trust-tech)" }}>{fmtUSD(total)}</div>
        </div>
      </div>
    </div>);

};

const ScreenAmount = ({ tweaks, draw, setDraw, onContinue, onBack }) => {
  const { offerAmount, partnerName } = tweaks;
  return (
    <div className="cap fade-up">
      <div className="cap-shell">
        <div className="cap-header">
          <CapitalCobrand partnerName={partnerName} attribution={tweaks.revenuedAttribution} />
          <button className="btn btn-text" onClick={onBack}><Icon name="arrow-left" size={14} /> Back</button>
        </div>

        <Steps step={1} total={6} labels={["Choose amount", "Connect bank", "Business info", "Owner info", "Review", "Sign"]} />

        <div className="mt-6 card" style={{
          marginTop: 28,
          padding: 0, overflow: "hidden",
          display: "grid", gridTemplateColumns: "minmax(0, 1.35fr) minmax(0, 1fr)"
        }}>
          {/* LEFT — input + slider + chips */}
          <div style={{ padding: "40px 44px" }}>
            <Eyebrow>How much do you want to draw?</Eyebrow>
            <h2 style={{
              fontFamily: "var(--font-primary)", fontWeight: 700,
              fontSize: 26, letterSpacing: "-0.02em", lineHeight: 1.2,
              margin: "10px 0 22px", color: "var(--trust-tech)"
            }}>
              Type a number, or drag the slider.
            </h2>

            <AmountField value={draw} onChange={setDraw} min={1000} max={offerAmount} />

            <div style={{ fontSize: 13, color: "var(--tt-60)", margin: "12px 0 30px" }}>
              Any amount from <span className="tnum" style={{ fontWeight: 600, color: "var(--tt-80)" }}>$1,000</span> up to <span className="tnum" style={{ fontWeight: 600, color: "var(--tt-80)" }}>{fmtUSD(offerAmount)}</span>. The rest stays on your line for when you need it.
            </div>

            <MoneySlider value={draw} min={1000} max={offerAmount} step={500} onChange={setDraw} />

            <div style={{ marginTop: 26 }}>
              <div style={{
                fontSize: 10.5, fontWeight: 700, letterSpacing: "0.14em",
                color: "var(--tt-40)", textTransform: "uppercase", marginBottom: 10
              }}>
                Quick select
              </div>
              <div style={{ display: "flex", gap: 8, flexWrap: "wrap" }}>
                {[10000, 25000, 50000, offerAmount].map((v) => {
                  const active = draw === v;
                  return (
                    <button key={v} onClick={() => setDraw(v)} style={{
                      background: active ? "var(--trust-tech)" : "#fff",
                      color: active ? "#fff" : "var(--trust-tech)",
                      border: "1px solid " + (active ? "var(--trust-tech)" : "var(--border-strong)"),
                      padding: "8px 14px", borderRadius: 999, fontSize: 13, fontWeight: 600,
                      cursor: "pointer", fontFamily: "inherit", fontVariantNumeric: "tabular-nums",
                      transition: "all 0.12s"
                    }}>
                      {v === offerAmount ? "Max · " + fmtUSD(v) : fmtUSD(v)}
                    </button>);

                })}
              </div>
            </div>
          </div>

          {/* RIGHT — Flex Line capacity dial */}
          <div style={{
            padding: "40px 36px",
            background: "linear-gradient(180deg, var(--tt-5) 0%, #fff 100%)",
            borderLeft: "1px solid var(--border-1)",
            display: "flex", flexDirection: "column", justifyContent: "center"
          }}>
            <FlexLineDial drawn={draw} total={offerAmount} partnerName={partnerName} />
          </div>
        </div>

        <div style={{ display: "flex", justifyContent: "flex-end", marginTop: 24, gap: 12 }}>
          <Button variant="dark" size="lg" onClick={onContinue} iconAfter="arrow-right">
            Continue with {fmtUSD(draw)}
          </Button>
        </div>
      </div>
    </div>);

};

// =====================================================================
// 3) PLAID CONNECTION
// =====================================================================
const ScreenPlaid = ({ tweaks, step, total, onContinue, onBack, draw }) => {
  const [status, setStatus] = React.useState("idle"); // idle → loading → success
  const [bank, setBank] = React.useState(null);

  const connect = (b) => {
    setBank(b);
    setStatus("loading");
    setTimeout(() => setStatus("success"), 1600);
  };

  return (
    <div className="cap fade-up">
      <div className="cap-shell">
        <div className="cap-header">
          <CapitalCobrand partnerName={tweaks.partnerName} attribution={tweaks.revenuedAttribution} />
          <button className="btn btn-text" onClick={onBack}><Icon name="arrow-left" size={14} /> Back</button>
        </div>

        <Steps step={step} total={total} />

        <div className="mt-6" style={{ marginTop: 28, display: "grid", gridTemplateColumns: "1fr 1fr", gap: 40, alignItems: "center" }}>
          <div>
            <Eyebrow>Step {step} of {total}</Eyebrow>
            <h2 style={{ fontSize: 36, fontWeight: 700, letterSpacing: "-0.02em", lineHeight: 1.1, margin: "12px 0 16px" }}>
              Connect your bank
            </h2>
            <p style={{ fontSize: 16, lineHeight: 1.55, color: "var(--tt-60)", margin: "0 0 20px", maxWidth: 460 }}>
              We use Plaid to verify your revenue and set up your weekly payment. It's the same connection your accounting software uses.
            </p>
            <div style={{ display: "flex", flexDirection: "column", gap: 12, maxWidth: 420 }}>
              {[
                { ic: "lock", t: "Bank-level security", d: "256-bit encryption. Plaid never shares your login with us." },
                { ic: "eye-off", t: "Read-only access", d: "We can see deposits, never move money out of this account." },
                { ic: "rotate-ccw", t: "You can revoke any time", d: "From your settings or your bank's app." }].
                map((p, i) =>
                  <div key={i} style={{ display: "flex", gap: 12, alignItems: "flex-start" }}>
                    <div style={{ width: 32, height: 32, borderRadius: 8, background: "var(--fp-10)", color: "var(--fp-100)", display: "grid", placeItems: "center", flexShrink: 0 }}>
                      <Icon name={p.ic} size={15} />
                    </div>
                    <div>
                      <div style={{ fontSize: 13.5, fontWeight: 600 }}>{p.t}</div>
                      <div style={{ fontSize: 12.5, color: "var(--tt-60)", marginTop: 2 }}>{p.d}</div>
                    </div>
                  </div>
                )}
            </div>

            {status === "success" &&
              <Button variant="dark" size="lg" onClick={onContinue} iconAfter="arrow-right" style={{ marginTop: 32 }}>
                Continue
              </Button>
            }
          </div>

          <div style={{ display: "grid", placeItems: "center" }}>
            <PlaidCard status={status} bank={bank} onConnect={connect} />
          </div>
        </div>
      </div>
    </div>);

};

// =====================================================================
// 4) BUSINESS INFORMATION
// =====================================================================
const ScreenBusiness = ({ tweaks, step, total, isPrefilled, onContinue, onBack }) => {
  const [data, setData] = React.useState({
    legalName: isPrefilled ? "Acme Coffee Roasters LLC" : "",
    dba: isPrefilled ? "Acme Coffee" : "",
    ein: isPrefilled ? "82-4501931" : "",
    industry: isPrefilled ? "Food service · Specialty coffee" : "",
    inception: isPrefilled ? "March 2022" : "",
    street: isPrefilled ? "412 Larkin St" : "",
    city: isPrefilled ? "San Francisco" : "",
    state: isPrefilled ? "CA" : "",
    zip: isPrefilled ? "94109" : "",
    monthlyRevenue: isPrefilled ? "85000" : "",
    employees: isPrefilled ? "8" : ""
  });
  const set = (k) => (e) => setData({ ...data, [k]: e.target.value });

  return (
    <div className="cap fade-up">
      <div className="cap-shell">
        <div className="cap-header">
          <CapitalCobrand partnerName={tweaks.partnerName} attribution={tweaks.revenuedAttribution} />
          <button className="btn btn-text" onClick={onBack}><Icon name="arrow-left" size={14} /> Back</button>
        </div>

        <Steps step={step} total={total} />

        <div className="mt-6" style={{ marginTop: 28 }}>
          <Eyebrow>Step {step} of {total}</Eyebrow>
          <h2 style={{ fontSize: 32, fontWeight: 700, letterSpacing: "-0.02em", margin: "10px 0 6px" }}>
            {isPrefilled ? "Confirm your business details" : "Tell us about your business"}
          </h2>
          <p style={{ fontSize: 15, color: "var(--tt-60)", margin: "0 0 24px", maxWidth: 540 }}>
            {isPrefilled ?
              `We already have what ${tweaks.partnerName} shared. Check it over and edit anything that's changed.` :
              "We'll use this to verify your business and set up your Flex Line."}
          </p>

          <div className="card card-pad" style={{ maxWidth: 720 }}>
            {isPrefilled &&
              <div style={{
                display: "flex", alignItems: "center", gap: 10,
                padding: "10px 14px", background: "var(--fp-5)",
                border: "1px solid var(--fp-20)", borderRadius: 8,
                fontSize: 12.5, color: "#075c3e", marginBottom: 22
              }}>
                <Icon name="check" size={14} color="var(--fp-100)" strokeWidth={2.5} />
                Pre-filled from your {tweaks.partnerName} account.
              </div>
            }

            <div style={{ display: "grid", gap: 18 }}>
              <div className="field-row">
                <TextInput label="Legal business name" value={data.legalName} onChange={set("legalName")} />
                <TextInput label="DBA / Trade name" value={data.dba} onChange={set("dba")} />
              </div>
              <div className="field-row">
                <TextInput label="EIN" value={data.ein} onChange={set("ein")} placeholder="XX-XXXXXXX" />
                <SelectInput
                  label="Industry"
                  value={data.industry}
                  onChange={set("industry")}
                  options={[
                    "Food service · Specialty coffee",
                    "Food service · Restaurant",
                    "Retail",
                    "Personal services",
                    "Auto · Repair",
                    "Construction"]
                  } />

              </div>
              <TextInput label="Business street address" value={data.street} onChange={set("street")} />
              <div className="field-row-3">
                <TextInput label="City" value={data.city} onChange={set("city")} />
                <TextInput label="State" value={data.state} onChange={set("state")} />
                <TextInput label="ZIP" value={data.zip} onChange={set("zip")} />
              </div>
              <div className="field-row">
                <TextInput label="Avg. monthly revenue" prefix="$" value={data.monthlyRevenue} onChange={set("monthlyRevenue")} hint="Used to size your Flex Line" />
                <TextInput label="Time in business" value={data.inception} onChange={set("inception")} hint="Approximate is fine" />
              </div>
            </div>
          </div>

          <div style={{ display: "flex", justifyContent: "flex-end", marginTop: 32 }}>
            <Button variant="dark" size="lg" onClick={onContinue} iconAfter="arrow-right">Continue</Button>
          </div>
        </div>
      </div>
    </div>);

};

// =====================================================================
// 5) OWNER INFORMATION
// =====================================================================
const ScreenOwner = ({ tweaks, step, total, isPrefilled, onContinue, onBack }) => {
  const [data, setData] = React.useState({
    firstName: isPrefilled ? "Sarah" : "",
    lastName: isPrefilled ? "Chen" : "",
    title: isPrefilled ? "Owner / President" : "",
    ownershipPct: isPrefilled ? "100" : "",
    email: isPrefilled ? "sarah@acmecoffee.co" : "",
    phone: isPrefilled ? "(415) 555-0142" : "",
    dob: isPrefilled ? "08/14/1987" : "",
    ssn: "•••-••-4391",
    street: isPrefilled ? "189 Oak Grove Ave" : "",
    city: isPrefilled ? "San Francisco" : "",
    state: isPrefilled ? "CA" : "",
    zip: isPrefilled ? "94110" : ""
  });
  const set = (k) => (e) => setData({ ...data, [k]: e.target.value });

  return (
    <div className="cap fade-up">
      <div className="cap-shell">
        <div className="cap-header">
          <CapitalCobrand partnerName={tweaks.partnerName} attribution={tweaks.revenuedAttribution} />
          <button className="btn btn-text" onClick={onBack}><Icon name="arrow-left" size={14} /> Back</button>
        </div>

        <Steps step={step} total={total} />

        <div className="mt-6" style={{ marginTop: 28 }}>
          <Eyebrow>Step {step} of {total}</Eyebrow>
          <h2 style={{ fontSize: 32, fontWeight: 700, letterSpacing: "-0.02em", margin: "10px 0 6px" }}>
            About the owner
          </h2>
          <p style={{ fontSize: 15, color: "var(--tt-60)", margin: "0 0 24px", maxWidth: 540 }}>
            We need to verify the principal of the business — a federal requirement, not a credit decision.
          </p>

          <div className="card card-pad" style={{ maxWidth: 720 }}>
            <div style={{ display: "grid", gap: 18 }}>
              <div className="field-row">
                <TextInput label="First name" value={data.firstName} onChange={set("firstName")} />
                <TextInput label="Last name" value={data.lastName} onChange={set("lastName")} />
              </div>
              <div className="field-row">
                <TextInput label="Title" value={data.title} onChange={set("title")} />
                <TextInput label="Ownership %" value={data.ownershipPct} onChange={set("ownershipPct")} />
              </div>
              <div className="field-row">
                <TextInput label="Email" type="email" value={data.email} onChange={set("email")} />
                <TextInput label="Mobile" value={data.phone} onChange={set("phone")} />
              </div>
              <div className="field-row">
                <TextInput label="Date of birth" value={data.dob} onChange={set("dob")} placeholder="MM/DD/YYYY" />
                <TextInput label="SSN" value={data.ssn} onChange={set("ssn")} hint="Encrypted and never displayed in full" />
              </div>
              <TextInput label="Home address" value={data.street} onChange={set("street")} />
              <div className="field-row-3">
                <TextInput label="City" value={data.city} onChange={set("city")} />
                <TextInput label="State" value={data.state} onChange={set("state")} />
                <TextInput label="ZIP" value={data.zip} onChange={set("zip")} />
              </div>
            </div>
          </div>

          <div style={{ display: "flex", justifyContent: "flex-end", marginTop: 32 }}>
            <Button variant="dark" size="lg" onClick={onContinue} iconAfter="arrow-right">Continue</Button>
          </div>
        </div>
      </div>
    </div>);

};

// =====================================================================
// 6) REVIEW & CONSENT
// =====================================================================
const ScreenReview = ({ tweaks, step, total, draw, hasOffer, onSubmit, onBack }) => {
  const { partnerName, factorRate } = tweaks;
  const [agree1, setAgree1] = React.useState(false);
  const [agree2, setAgree2] = React.useState(false);
  const canSubmit = agree1 && agree2;
  const terms = draw ? computeTerms(draw, factorRate) : null;

  const Row = ({ k, v }) =>
    <div style={{ display: "flex", justifyContent: "space-between", padding: "10px 0", borderBottom: "1px solid var(--border-1)", fontSize: 13 }}>
      <span style={{ color: "var(--tt-60)" }}>{k}</span>
      <span style={{ fontWeight: 600, textAlign: "right" }}>{v}</span>
    </div>;


  return (
    <div className="cap fade-up">
      <div className="cap-shell">
        <div className="cap-header">
          <CapitalCobrand partnerName={partnerName} attribution={tweaks.revenuedAttribution} />
          <button className="btn btn-text" onClick={onBack}><Icon name="arrow-left" size={14} /> Back</button>
        </div>

        <Steps step={step} total={total} />

        <div className="mt-6" style={{ marginTop: 28 }}>
          <Eyebrow>Step {step} of {total}</Eyebrow>
          <h2 style={{ fontSize: 32, fontWeight: 700, letterSpacing: "-0.02em", margin: "10px 0 6px" }}>
            Review and submit
          </h2>
          <p style={{ fontSize: 15, color: "var(--tt-60)", margin: "0 0 24px", maxWidth: 540 }}>
            Last look. After this we'll run a soft check and confirm your final terms.
          </p>

          <div style={{ display: "grid", gridTemplateColumns: hasOffer ? "1fr 1fr" : "1fr", gap: 16 }}>
            {hasOffer && terms &&
              <div className="card card-pad">
                <div style={{ display: "flex", alignItems: "center", gap: 10, marginBottom: 12 }}>
                  <Eyebrow>Your offer</Eyebrow>
                  <span className="pill pill-teal">Pre-approved</span>
                </div>
                <Row k="Draw amount" v={fmtUSD(draw)} />
                <Row k="Factor rate" v={factorRate.toFixed(2)} />
                <Row k="Total payback" v={fmtUSD(terms.payback)} />
                <Row k="Est. weekly payment" v={"~" + fmtUSD(terms.weekly)} />
                <Row k="Est. payback period" v={"~" + terms.months + " months"} />
              </div>
            }
            <div className="card card-pad">
              <Eyebrow muted>Business</Eyebrow>
              <div style={{ marginTop: 12 }}>
                <Row k="Legal name" v="Acme Coffee Roasters LLC" />
                <Row k="DBA" v="Acme Coffee" />
                <Row k="EIN" v="82-4501931" />
                <Row k="Industry" v="Specialty coffee" />
                <Row k="Address" v="412 Larkin St, San Francisco CA 94109" />
                <Row k="Avg. monthly revenue" v="$85,000" />
              </div>
            </div>
          </div>

          <div className="card card-pad" style={{ marginTop: 16 }}>
            <Eyebrow muted>Owner</Eyebrow>
            <div style={{ marginTop: 12, display: "grid", gridTemplateColumns: "1fr 1fr", gap: "0 32px" }}>
              <Row k="Name" v="Sarah Chen" />
              <Row k="Title" v="Owner / President" />
              <Row k="Ownership" v="100%" />
              <Row k="DOB" v="08/14/1987" />
              <Row k="Email" v="sarah@acmecoffee.co" />
              <Row k="Phone" v="(415) 555-0142" />
              <Row k="SSN" v="•••-••-4391" />
              <Row k="Home address" v="189 Oak Grove Ave, SF CA 94110" />
            </div>
          </div>

          <div className="card card-pad" style={{ marginTop: 16 }}>
            <Eyebrow muted>Consent</Eyebrow>
            <div style={{ marginTop: 14, display: "flex", flexDirection: "column", gap: 12 }}>
              <Check checked={agree1} onChange={(e) => setAgree1(e.target.checked)}>
                I agree to Revenued's <a href="#" style={{ color: "var(--growth-galaxy)", fontWeight: 600 }}>Terms of Service</a> and <a href="#" style={{ color: "var(--growth-galaxy)", fontWeight: 600 }}>Privacy Policy</a>.
              </Check>
              <Check checked={agree2} onChange={(e) => setAgree2(e.target.checked)}>
                I authorize Revenued to perform a background and credit review, and to verify the information I've provided.
              </Check>
            </div>
            <div style={{ marginTop: 18 }}>
              <Disclosure>
                Revenued's service provides for the purchase of future receivables and is not a loan. Approval, advance amount, and pricing are determined by Revenued at its discretion based on the seller's revenue and business profile.
              </Disclosure>
            </div>
          </div>

          <div style={{ display: "flex", justifyContent: "flex-end", marginTop: 32 }}>
            <Button variant="dark" size="lg" disabled={!canSubmit} onClick={onSubmit} iconAfter="arrow-right">
              {hasOffer ? "Submit for final review" : "Submit application"}
            </Button>
          </div>
        </div>
      </div>
    </div>);

};

// =====================================================================
// 7a) REVIEWING STATE — value-add waiting screen
// =====================================================================
const ReviewingState = ({ tweaks, onView }) => {
  const { partnerName } = tweaks;

  const steps = [
    { label: "Verifying business identity", done: "Acme Coffee Roasters LLC", duration: 1400 },
    { label: `Analyzing ${partnerName} deposits`, done: "$85K/mo avg revenue", duration: 1700 },
    { label: "Pulling SBFE business credit", done: "Score 728 · Good", duration: 1700 },
    { label: "Calculating your final terms", done: "Approved up to $75,000", duration: 1600 }];

  const totalMs = steps.reduce((a, s) => a + s.duration, 0);

  const [elapsed, setElapsed] = React.useState(0);
  const [done, setDone] = React.useState(false);
  const startRef = React.useRef(null);

  React.useEffect(() => {
    startRef.current = performance.now();
    let raf;
    const tick = (now) => {
      const e = now - startRef.current;
      setElapsed(Math.min(e, totalMs));
      if (e >= totalMs) { setDone(true); return; }
      raf = requestAnimationFrame(tick);
    };
    raf = requestAnimationFrame(tick);
    return () => cancelAnimationFrame(raf);
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, []);

  const progress = elapsed / totalMs * 100;
  // Step cursor still drives the per-step checked/active state and value reveals.
  let stepCursor = steps.length;
  {
    let acc = 0;
    for (let i = 0; i < steps.length; i++) {
      const end = acc + steps[i].duration;
      if (elapsed < end) { stepCursor = i; break; }
      acc = end;
    }
  }
  const elapsedSec = Math.floor(elapsed / 1000);

  // SBFE score reveal — animates in as the credit-check step completes
  const creditStepStart = steps[0].duration + steps[1].duration;
  const creditStepEnd = creditStepStart + steps[2].duration;
  const sbfeReveal = Math.max(0, Math.min(1, (elapsed - creditStepStart) / (creditStepEnd - creditStepStart)));
  const sbfeTarget = 728;
  const sbfeDisplay = Math.round(300 + (sbfeTarget - 300) * sbfeReveal);

  return (
    <div className="cap fade-up">
      <div className="cap-shell">
        <div className="cap-header">
          <CapitalCobrand partnerName={partnerName} attribution={tweaks.revenuedAttribution} />
        </div>

        {/* Progress strip */}
        <div style={{
          marginTop: 8, marginBottom: 28,
          padding: "22px 24px",
          background: "var(--trust-tech)", color: "#fff",
          borderRadius: 16, position: "relative", overflow: "hidden"
        }}>
          <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center", marginBottom: 14 }}>
            <div>
              <div style={{ fontSize: 11, fontWeight: 700, letterSpacing: "0.14em", textTransform: "uppercase", color: "var(--funding-pool)", marginBottom: 4 }}>
                {done ? "Decision ready" : "Reviewing your application"}
              </div>
              <div style={{ fontSize: 20, fontWeight: 700, letterSpacing: "-0.01em" }}>
                {done ? "Your offer is ready to review." : "Hang tight — we'll be done in a few seconds."}
              </div>
            </div>
            <div style={{ display: "flex", alignItems: "center", gap: 14 }}>
              <div style={{ fontSize: 12, color: "rgba(255,255,255,0.6)", fontVariantNumeric: "tabular-nums" }}>
                {done ? "Complete" : `~${Math.max(0, Math.ceil((totalMs - elapsed) / 1000))}s remaining`}
              </div>
              <button
                onClick={onView}
                disabled={!done}
                className={done ? "btn btn-teal" : ""}
                style={!done ? {
                  background: "rgba(255,255,255,0.08)", color: "rgba(255,255,255,0.5)",
                  border: "1px solid rgba(255,255,255,0.14)", borderRadius: 999,
                  padding: "9px 18px", fontSize: 13, fontWeight: 600,
                  fontFamily: "inherit", cursor: "not-allowed",
                  display: "inline-flex", alignItems: "center", gap: 6
                } : { borderRadius: 999, padding: "9px 18px", fontSize: 13 }}>
                {done ? <>View decision <Icon name="arrow-right" size={14} /></> : <>View decision</>}
              </button>
            </div>
          </div>

          <div style={{ position: "relative", height: 6, background: "rgba(255,255,255,0.10)", borderRadius: 999, overflow: "hidden" }}>
            <div style={{
              width: `${progress}%`, height: "100%",
              background: "linear-gradient(90deg, var(--funding-pool) 0%, var(--bright-opportunity) 100%)",
              borderRadius: 999
            }} />
          </div>

          <div style={{ marginTop: 14, display: "grid", gridTemplateColumns: `repeat(${steps.length}, 1fr)`, gap: 12 }}>
            {steps.map((s, i) => {
              const isDone = i < stepCursor;
              const isActive = i === stepCursor;
              return (
                <div key={i} style={{ display: "flex", alignItems: "flex-start", gap: 8, fontSize: 12 }}>
                  <div
                    className={"rs-indicator" + (isDone ? " done" : isActive ? " active" : "")}
                    style={{
                      width: 16, height: 16, borderRadius: "50%",
                      display: "grid", placeItems: "center",
                      background: isDone ? "var(--funding-pool)" : isActive ? "rgba(4,196,158,0.18)" : "rgba(255,255,255,0.08)",
                      border: isDone ? "none" : isActive ? "1px solid var(--funding-pool)" : "1px solid rgba(255,255,255,0.18)",
                      flexShrink: 0, marginTop: 1,
                      transition: "background 0.3s ease-out, border-color 0.3s ease-out"
                    }}>
                    {isDone ?
                      <span className="rs-check">
                        <Icon name="check" size={11} color="var(--trust-tech)" strokeWidth={3} />
                      </span> :
                      isActive ? <div style={{ width: 6, height: 6, borderRadius: "50%", background: "var(--funding-pool)" }} className="pulse" /> : null}
                  </div>
                  <div style={{ minWidth: 0 }}>
                    <div style={{
                      color: isDone || isActive ? "rgba(255,255,255,0.92)" : "rgba(255,255,255,0.45)",
                      fontWeight: isActive ? 600 : 500,
                      lineHeight: 1.3,
                      transition: "color 0.3s ease-out"
                    }}>
                      {s.label}
                    </div>
                    <div style={{
                      fontSize: 11.5,
                      color: isDone ? "var(--funding-pool)" : "rgba(255,255,255,0.4)",
                      fontWeight: 600,
                      marginTop: 3,
                      opacity: isDone ? 1 : 0,
                      transform: isDone ? "translateY(0)" : "translateY(4px)",
                      transition: "opacity 0.35s ease-out, transform 0.35s cubic-bezier(0.2,0,0,1)",
                      whiteSpace: "nowrap",
                      overflow: "hidden",
                      textOverflow: "ellipsis"
                    }}>
                      {s.done}
                    </div>
                  </div>
                </div>);
            })}
          </div>
        </div>

        {/* Two-column content while waiting */}
        <div style={{ display: "grid", gridTemplateColumns: "minmax(0, 1.25fr) minmax(0, 1fr)", gap: 20 }}>
          {/* LEFT — Flex Line product video + value props */}
          <div className="card" style={{ padding: 0, overflow: "hidden", display: "flex", flexDirection: "column" }}>
            <FlexLineVideo />
            <div style={{ padding: "22px 26px 24px" }}>
              <div style={{ fontSize: 11, fontWeight: 700, letterSpacing: "0.14em", textTransform: "uppercase", color: "var(--growth-galaxy)", marginBottom: 8 }}>
                While you wait
              </div>
              <h3 style={{ fontSize: 22, fontWeight: 700, letterSpacing: "-0.015em", margin: "0 0 8px", color: "var(--trust-tech)" }}>
                Meet your Flex Line.
              </h3>
              <p style={{ fontSize: 14, color: "var(--tt-60)", lineHeight: 1.55, margin: "0 0 18px" }}>
                One reusable line of working capital. Draw what you need today, pull more later — payback adjusts to your revenue, not the calendar.
              </p>
              <div style={{ display: "grid", gridTemplateColumns: "repeat(3, 1fr)", gap: 12 }}>
                {[
                  { ic: "refresh-ccw", t: "Reusable", d: "Pay down, pull more" },
                  { ic: "activity", t: "Revenue-paced", d: "Weekly, from deposits" },
                  { ic: "zap", t: "Same-day", d: "Funds in 24 hours" }].
                  map((p, i) =>
                    <div key={i} style={{ padding: "14px 12px", border: "1px solid var(--border-1)", borderRadius: 10, background: "var(--tt-5)" }}>
                      <div style={{ width: 28, height: 28, borderRadius: 7, background: "var(--gg-5)", color: "var(--growth-galaxy)", display: "grid", placeItems: "center", marginBottom: 8 }}>
                        <Icon name={p.ic} size={15} />
                      </div>
                      <div style={{ fontSize: 12.5, fontWeight: 700, color: "var(--trust-tech)" }}>{p.t}</div>
                      <div style={{ fontSize: 11.5, color: "var(--tt-60)", marginTop: 2 }}>{p.d}</div>
                    </div>)}
              </div>
            </div>
          </div>

          {/* RIGHT — SBFE Business Credit Score */}
          <SBFECard score={sbfeDisplay} target={sbfeTarget} reveal={sbfeReveal} />
        </div>
      </div>

      <style>{`
        @keyframes pulse-dot {
          0%, 100% { transform: scale(1); opacity: 1; }
          50% { transform: scale(1.35); opacity: 0.7; }
        }
        .pulse { animation: pulse-dot 1.1s ease-in-out infinite; }
        @keyframes rs-check-pop {
          0%   { transform: scale(0.2); opacity: 0; }
          55%  { transform: scale(1.25); opacity: 1; }
          100% { transform: scale(1); }
        }
        .rs-indicator.done .rs-check {
          display: inline-flex;
          animation: rs-check-pop 0.45s cubic-bezier(0.34, 1.56, 0.64, 1) both;
        }
      `}</style>
    </div>);
};

const FlexLineVideo = () => {
  return (
    <div style={{
      position: "relative",
      aspectRatio: "16 / 9",
      background: "linear-gradient(135deg, var(--trust-tech) 0%, var(--growth-galaxy) 100%)",
      overflow: "hidden",
      cursor: "pointer"
    }} className="flex-video">
      {/* Ambient rings */}
      <div style={{ position: "absolute", right: -80, top: -80, opacity: 0.5 }}>
        <Rings size={300} palette="teal" />
      </div>
      <div style={{ position: "absolute", left: -60, bottom: -80, opacity: 0.35 }}>
        <Rings size={220} palette="light" />
      </div>

      {/* Floating money tile mockup */}
      <div style={{
        position: "absolute", left: "10%", top: "22%",
        background: "rgba(255,255,255,0.94)",
        padding: "14px 18px", borderRadius: 12,
        boxShadow: "0 12px 32px rgba(0,18,43,0.25)",
        transform: "rotate(-4deg)"
      }}>
        <div style={{ fontSize: 9, fontWeight: 700, letterSpacing: "0.14em", color: "var(--tt-60)", textTransform: "uppercase" }}>Available</div>
        <div className="tnum" style={{ fontFamily: "var(--font-primary)", fontSize: 22, fontWeight: 700, color: "var(--trust-tech)", letterSpacing: "-0.01em" }}>$75,000</div>
      </div>

      {/* Play button */}
      <div style={{
        position: "absolute", inset: 0,
        display: "grid", placeItems: "center"
      }}>
        <div style={{
          width: 72, height: 72, borderRadius: "50%",
          background: "rgba(255,255,255,0.95)",
          display: "grid", placeItems: "center",
          boxShadow: "0 16px 40px rgba(0,18,43,0.3)",
          transition: "transform 0.18s"
        }} className="play-btn">
          <div style={{
            width: 0, height: 0,
            borderLeft: "18px solid var(--trust-tech)",
            borderTop: "12px solid transparent",
            borderBottom: "12px solid transparent",
            marginLeft: 5
          }} />
        </div>
      </div>

      {/* Footer label */}
      <div style={{
        position: "absolute", left: 18, bottom: 16,
        display: "flex", alignItems: "center", gap: 10,
        color: "#fff"
      }}>
        <div style={{
          padding: "4px 10px", background: "rgba(0,0,0,0.35)", borderRadius: 4,
          fontSize: 11, fontWeight: 600,
          backdropFilter: "blur(4px)"
        }}>
          1:24
        </div>
        <div style={{ fontSize: 13, fontWeight: 600 }}>How the Flex Line works</div>
      </div>

      <style>{`
        .flex-video:hover .play-btn { transform: scale(1.06); }
      `}</style>
    </div>);
};

const SBFECard = ({ score, target, reveal }) => {
  // SBFE scale: 300–850. Bands: Poor / Fair / Good / Excellent.
  const min = 300, max = 850;
  const pct = (score - min) / (max - min) * 100;
  const bands = [
    { label: "Poor", from: 300, to: 579, color: "#e07a5f" },
    { label: "Fair", from: 580, to: 669, color: "#e0a85f" },
    { label: "Good", from: 670, to: 739, color: "#04C49E" },
    { label: "Excellent", from: 740, to: 850, color: "#0040BA" }];

  const tier = bands.find((b) => score >= b.from && score <= b.to) || bands[0];
  const revealed = reveal > 0.05;

  return (
    <div className="card" style={{ padding: "22px 24px", display: "flex", flexDirection: "column", gap: 16 }}>
      <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between" }}>
        <div>
          <div style={{ fontSize: 11, fontWeight: 700, letterSpacing: "0.14em", textTransform: "uppercase", color: "var(--tt-60)", marginBottom: 4 }}>
            Business credit
          </div>
          <div style={{ fontSize: 13.5, fontWeight: 600, color: "var(--trust-tech)" }}>
            SBFE Score · pulled today
          </div>
        </div>
        <div style={{
          padding: "5px 11px", borderRadius: 999,
          fontSize: 11, fontWeight: 700, letterSpacing: "0.06em",
          background: revealed ? "rgba(4,196,158,0.10)" : "var(--tt-5)",
          color: revealed ? "#047a62" : "var(--tt-60)",
          border: "1px solid " + (revealed ? "rgba(4,196,158,0.30)" : "var(--border-1)"),
          display: "inline-flex", alignItems: "center", gap: 6,
          transition: "all 0.4s"
        }}>
          {revealed ? <><Icon name="check" size={11} strokeWidth={3} color="#047a62" /> Verified</> : <>Pulling…</>}
        </div>
      </div>

      <div style={{ textAlign: "center", padding: "8px 0 4px" }}>
        <div className="tnum" style={{
          fontFamily: "var(--font-primary)", fontWeight: 700,
          fontSize: 64, letterSpacing: "-0.025em", lineHeight: 1,
          color: revealed ? "var(--trust-tech)" : "var(--tt-40)",
          transition: "color 0.4s"
        }}>
          {score}
        </div>
        <div style={{ fontSize: 11.5, color: "var(--tt-60)", marginTop: 6, fontVariantNumeric: "tabular-nums" }}>
          out of {max}
        </div>
        <div style={{
          marginTop: 10,
          display: "inline-flex", alignItems: "center", gap: 8,
          padding: "5px 12px", borderRadius: 999,
          background: revealed ? tier.color + "22" : "var(--tt-5)",
          color: revealed ? tier.color : "var(--tt-60)",
          fontSize: 12, fontWeight: 700, letterSpacing: "0.04em",
          opacity: revealed ? 1 : 0.5, transition: "all 0.4s"
        }}>
          <span style={{ width: 7, height: 7, borderRadius: "50%", background: revealed ? tier.color : "var(--tt-40)" }} />
          {revealed ? tier.label.toUpperCase() : "ANALYZING"}
        </div>
      </div>

      {/* Band rail */}
      <div style={{ position: "relative", padding: "40px 0 8px" }}>
        <div style={{ display: "flex", height: 10, borderRadius: 999, overflow: "hidden", border: "1px solid var(--border-1)" }}>
          {bands.map((b, i) => {
            const w = (b.to - b.from) / (max - min) * 100;
            return <div key={i} style={{ width: `${w}%`, background: b.color, opacity: 0.85 }} />;
          })}
        </div>
        {/* Marker — sits above the band */}
        <div style={{
          position: "absolute",
          left: `${pct}%`, top: 8,
          transform: "translateX(-50%)",
          display: "flex", flexDirection: "column", alignItems: "center",
          opacity: revealed ? 1 : 0,
          transition: "left 0.2s ease-out, opacity 0.3s",
          pointerEvents: "none"
        }}>
          <div style={{
            padding: "3px 9px", borderRadius: 6,
            background: "var(--trust-tech)", color: "#fff",
            fontSize: 10.5, fontWeight: 700, lineHeight: 1.2,
            fontVariantNumeric: "tabular-nums",
            whiteSpace: "nowrap"
          }}>
            you
          </div>
          <div style={{ width: 2, height: 12, background: "var(--trust-tech)" }} />
        </div>
        <div style={{ display: "flex", justifyContent: "space-between", marginTop: 10, fontSize: 10.5, color: "var(--tt-60)", fontVariantNumeric: "tabular-nums" }}>
          {bands.map((b, i) => <span key={i}>{b.from}</span>)}
          <span>{max}</span>
        </div>
      </div>

      {/* Contributing factors */}
      <div style={{ borderTop: "1px solid var(--border-1)", paddingTop: 14, display: "flex", flexDirection: "column", gap: 10, opacity: revealed ? 1 : 0.4, transition: "opacity 0.4s" }}>
        {[
          { label: "Payment history", value: "Excellent", delta: "+12 mo" },
          { label: "Revenue stability", value: "Strong", delta: "12-mo trend ↑" },
          { label: "Time in business", value: "3.1 yrs", delta: "" }].
          map((f, i) =>
            <div key={i} style={{ display: "flex", alignItems: "baseline", justifyContent: "space-between", fontSize: 12.5 }}>
              <span style={{ color: "var(--tt-60)" }}>{f.label}</span>
              <span>
                <span style={{ fontWeight: 700, color: "var(--trust-tech)" }}>{f.value}</span>
                {f.delta && <span style={{ marginLeft: 8, color: "var(--tt-60)", fontSize: 11.5 }}>{f.delta}</span>}
              </span>
            </div>)}
      </div>
    </div>);
};

// =====================================================================
// 7) HARD OFFER / DECISION — 3 offer options
// =====================================================================
const buildOffer = ({ tag, limit, factor, days }) => {
  const payback = limit * factor;
  const daily = Math.round(payback / days);
  // Simple-interest APR approximation for an evenly-amortizing advance:
  // APR ≈ 2 · (factor − 1) · 365 / term_days.
  const apr = 2 * (factor - 1) * 365 / days * 100;
  return { tag, limit, factor, days, daily, apr, payback };
};

const OfferCard = ({ offer, selected, recommended, onSelect }) => {
  const dark = recommended;
  const factorFmt = offer.factor.toFixed(2);

  const rows = [
    { l: "Factor rate", v: factorFmt },
    { l: "Payback period", v: offer.days + " days" },
    { l: "Estimated daily payment", v: fmtUSD(offer.daily) }];


  // Color tokens shift between the dark (recommended) and light cards.
  const c = dark ? {
    bg: "var(--trust-tech)",
    border: selected ? "var(--funding-pool)" : "var(--trust-tech)",
    fg: "#fff",
    fgMuted: "rgba(255,255,255,0.62)",
    statLabel: "rgba(255,255,255,0.55)",
    statValue: "#fff",
    divider: "rgba(255,255,255,0.10)",
    accent: "var(--funding-pool)"
  } : {
    bg: "#fff",
    border: selected ? "var(--growth-galaxy)" : "var(--border-1)",
    fg: "var(--trust-tech)",
    fgMuted: "var(--tt-60)",
    statLabel: "var(--tt-60)",
    statValue: "var(--trust-tech)",
    divider: "var(--border-1)",
    accent: "var(--growth-galaxy)"
  };

  return (
    <button
      onClick={onSelect}
      className="offer-card"
      style={{
        position: "relative",
        textAlign: "left", cursor: "pointer",
        background: c.bg, color: c.fg,
        border: `1.5px solid ${c.border}`,
        borderRadius: 18,
        padding: "26px 24px 22px",
        font: "inherit",
        boxShadow: selected ?
          dark ? "0 16px 40px rgba(0,18,43,0.35)" : "0 12px 32px rgba(0,64,186,0.14)" :
          dark ? "0 8px 24px rgba(0,18,43,0.20)" : "var(--shadow-sm)",
        transition: "transform 140ms cubic-bezier(0.2,0,0,1), box-shadow 140ms, border-color 140ms",
        overflow: "hidden",
        transform: selected ? "translateY(-2px)" : "translateY(0)",
        display: "flex", flexDirection: "column", gap: 18,
        minWidth: 0
      }}>
      {dark &&
        <div style={{ position: "absolute", right: -60, top: -60, opacity: 0.55, pointerEvents: "none" }}>
          <Rings size={240} palette="teal" />
        </div>
      }

      <div style={{ position: "relative", display: "flex", alignItems: "center", justifyContent: "space-between", gap: 8 }}>
        <div style={{
          display: "inline-flex", alignItems: "center", gap: 6,
          padding: "5px 11px 5px 9px",
          borderRadius: 999,
          background: dark ? "rgba(4,196,158,0.16)" : "var(--gg-5)",
          border: `1px solid ${dark ? "rgba(4,196,158,0.32)" : "var(--gg-10)"}`,
          fontSize: 10.5, fontWeight: 700, letterSpacing: "0.12em",
          textTransform: "uppercase",
          color: dark ? "var(--funding-pool)" : "var(--growth-galaxy)"
        }}>
          {dark && <span style={{ width: 5, height: 5, borderRadius: "50%", background: "var(--funding-pool)" }} />}
          {offer.tag}
        </div>

        <div style={{
          width: 22, height: 22, borderRadius: "50%",
          background: selected ? c.accent : "transparent",
          border: `1.5px solid ${selected ? c.accent : dark ? "rgba(255,255,255,0.30)" : "var(--border-strong)"}`,
          display: "grid", placeItems: "center",
          transition: "background 140ms, border-color 140ms"
        }}>
          {selected && <Icon name="check" size={12} color={dark ? "var(--trust-tech)" : "#fff"} strokeWidth={3} />}
        </div>
      </div>

      <div style={{ position: "relative" }}>
        <div style={{
          fontSize: 11, fontWeight: 700, letterSpacing: "0.14em",
          color: c.statLabel, textTransform: "uppercase", marginBottom: 8
        }}>
          Spending limit
        </div>
        <div className="tnum" style={{
          fontFamily: "var(--font-primary)", fontWeight: 700,
          fontSize: "clamp(36px, 4.2vw, 52px)", lineHeight: 1,
          letterSpacing: "-0.025em",
          color: c.fg,
          whiteSpace: "nowrap"
        }}>
          {fmtUSD(offer.limit)}
        </div>
      </div>

      <div style={{
        height: 1, background: c.divider, margin: 0
      }} />

      <div style={{ position: "relative", display: "flex", flexDirection: "column", gap: 10 }}>
        {rows.map((r, i) =>
          <div key={i} style={{ display: "flex", alignItems: "baseline", justifyContent: "space-between", gap: 8, fontSize: 13 }}>
            <span style={{ color: c.statLabel }}>{r.l}</span>
            <span className="tnum" style={{ fontWeight: 700, color: c.statValue }}>{r.v}</span>
          </div>)}
      </div>

      <div style={{ position: "relative", marginTop: 4 }}>
        {selected ?
          <div style={{
            display: "inline-flex", alignItems: "center", gap: 6,
            fontSize: 12, fontWeight: 600,
            color: c.accent
          }}>
            <Icon name="check-circle" size={14} color={c.accent} />
            Selected
          </div> :

          <div style={{
            display: "inline-flex", alignItems: "center", gap: 6,
            fontSize: 12, fontWeight: 600,
            color: c.fgMuted
          }}>
            Choose this offer
            <Icon name="arrow-right" size={13} color={c.fgMuted} />
          </div>
        }
      </div>

      <style>{`
        .offer-card:hover {
          transform: translateY(-3px);
        }
      `}</style>
    </button>);
};

const ScreenDecision = ({ tweaks, draw, setDraw, hasOffer, onContinue, onBack, onSelectOffer }) => {
  // Warm flow: confirmation of the offer they already selected.
  // Cold flow: pick from three approved options.
  const { partnerName } = tweaks;
  const [reviewing, setReviewing] = React.useState(true);
  const [selected, setSelected] = React.useState(1); // default to "Most popular"
  const approvedMax = hasOffer ? tweaks.offerAmount : 50000;

  // 3 offers: compact / standard / max — bigger limit pairs with higher factor + longer term.
  // Round limits to clean $500 increments.
  const round500 = (n) => Math.round(n / 500) * 500;
  const offers = [
    buildOffer({ tag: "Fastest payback", limit: round500(approvedMax * 0.5), factor: 1.22, days: 200 }),
    buildOffer({ tag: "Most popular", limit: round500(approvedMax * 0.75), factor: tweaks.factorRate, days: 260 }),
    buildOffer({ tag: "Largest line", limit: approvedMax, factor: 1.38, days: 320 })];


  const recommendedIdx = 1;
  const sel = offers[selected];

  // Initial draw amount — defaults to incoming `draw` (set on the Amount screen)
  // clamped to the selected offer's limit. Falls back to the full limit when no
  // prior draw was chosen (cold flow path).
  const clampDraw = (v, lim) => Math.min(lim, Math.max(1000, v || lim));
  const [initialDraw, setInitialDraw] = React.useState(() => clampDraw(draw, sel.limit));

  // When the user picks a different offer, clamp the initial draw to the new
  // limit (or reset to the new full limit if it was at the old max).
  React.useEffect(() => {
    setInitialDraw((prev) => clampDraw(prev, sel.limit));
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [sel.limit]);

  if (reviewing) {
    return <ReviewingState tweaks={tweaks} onView={() => setReviewing(false)} />;
  }

  return (
    <div className="cap fade-up">
      <div className="cap-shell">
        <div className="cap-header">
          <CapitalCobrand partnerName={partnerName} attribution={tweaks.revenuedAttribution} />
          <button className="btn btn-text" onClick={onBack}><Icon name="arrow-left" size={14} /> Back</button>
        </div>

        {/* Approved banner — compact, makes room for the offer cards */}
        <div className="card card-pad" style={{
          background: "linear-gradient(135deg, var(--funding-pool) 0%, #048468 100%)",
          color: "#fff", borderRadius: 18, border: "none",
          position: "relative", overflow: "hidden",
          padding: "22px 28px",
          display: "flex", alignItems: "center", justifyContent: "space-between", gap: 18, flexWrap: "wrap"
        }}>
          <div style={{ position: "absolute", right: -60, top: -60, opacity: 0.55, pointerEvents: "none" }}>
            <Rings size={260} palette="light" />
          </div>
          <div style={{ position: "relative", display: "flex", alignItems: "center", gap: 16 }}>
            <div style={{
              width: 44, height: 44, borderRadius: 12,
              background: "rgba(255,255,255,0.18)",
              display: "grid", placeItems: "center", flexShrink: 0
            }}>
              <Icon name="check" size={24} color="#fff" strokeWidth={3} />
            </div>
            <div>
              <div style={{
                fontSize: 10.5, fontWeight: 700, letterSpacing: "0.16em",
                color: "rgba(255,255,255,0.78)", textTransform: "uppercase", marginBottom: 4
              }}>
                Approved · 3 offers ready
              </div>
              <div style={{ fontSize: 22, fontWeight: 700, letterSpacing: "-0.015em", lineHeight: 1.2 }}>
                Three ways to take your Flex Line.
              </div>
            </div>
          </div>
          <div style={{ position: "relative", fontSize: 13.5, color: "rgba(255,255,255,0.82)", maxWidth: 320, lineHeight: 1.5 }}>
            Pick the option that fits your business. You can adjust later from your dashboard.
          </div>
        </div>

        {/* 3 offer cards */}
        <div className="mt-6" style={{
          marginTop: 20,
          display: "grid",
          gridTemplateColumns: "repeat(3, minmax(0, 1fr))",
          gap: 16,
          alignItems: "stretch"
        }}>
          {offers.map((o, i) =>
            <OfferCard
              key={i}
              offer={o}
              selected={selected === i}
              recommended={i === recommendedIdx}
              onSelect={() => setSelected(i)} />)}
        </div>

        {/* Initial draw amount */}
        <div className="card" style={{ marginTop: 20, padding: 0, overflow: "hidden" }}>
          <div style={{
            display: "flex", alignItems: "center", justifyContent: "space-between",
            padding: "20px 28px",
            borderBottom: "1px solid var(--border-1)",
            background: "linear-gradient(180deg, var(--tt-5) 0%, #fff 100%)"
          }}>
            <div>
              <Eyebrow>Step 2 · Initial draw</Eyebrow>
              <div style={{
                fontFamily: "var(--font-primary)", fontWeight: 700,
                fontSize: 22, letterSpacing: "-0.015em", lineHeight: 1.2,
                color: "var(--trust-tech)", marginTop: 6
              }}>
                How much do you want to take right now?
              </div>
              <div style={{ fontSize: 13, color: "var(--tt-60)", marginTop: 4, maxWidth: 540 }}>
                You can pull more later — the rest stays on your Flex Line, ready when you need it.
              </div>
            </div>
            <div style={{ textAlign: "right" }}>
              <div style={{ fontSize: 10, fontWeight: 700, letterSpacing: "0.14em", color: "var(--tt-60)", textTransform: "uppercase", marginBottom: 4 }}>
                Selected line
              </div>
              <div className="tnum" style={{ fontFamily: "var(--font-primary)", fontSize: 22, fontWeight: 700, color: "var(--trust-tech)", letterSpacing: "-0.01em" }}>
                {fmtUSD(sel.limit)}
              </div>
            </div>
          </div>

          <div style={{
            padding: "26px 28px 24px",
            display: "grid", gridTemplateColumns: "minmax(0, auto) minmax(0, 1fr)",
            gap: 32, alignItems: "center"
          }}>
            <div>
              <AmountField value={initialDraw} onChange={setInitialDraw} min={1000} max={sel.limit} />
              <div style={{ fontSize: 12, color: "var(--tt-60)", marginTop: 10, fontVariantNumeric: "tabular-nums" }}>
                $1,000 minimum · {fmtUSD(sel.limit)} maximum
              </div>
            </div>

            <div>
              <MoneySlider value={initialDraw} min={1000} max={sel.limit} step={500} onChange={setInitialDraw} />

              <div style={{ marginTop: 22, display: "flex", alignItems: "center", gap: 10, flexWrap: "wrap" }}>
                <span style={{ fontSize: 10.5, fontWeight: 700, letterSpacing: "0.14em", color: "var(--tt-40)", textTransform: "uppercase" }}>
                  Quick select
                </span>
                {[
                  { v: Math.max(1000, round500(sel.limit * 0.25)), l: "25%" },
                  { v: Math.max(1000, round500(sel.limit * 0.5)), l: "50%" },
                  { v: Math.max(1000, round500(sel.limit * 0.75)), l: "75%" },
                  { v: sel.limit, l: "Max" }].
                  map((p, i) => {
                    const active = initialDraw === p.v;
                    return (
                      <button key={i} onClick={() => setInitialDraw(p.v)} style={{
                        background: active ? "var(--trust-tech)" : "#fff",
                        color: active ? "#fff" : "var(--trust-tech)",
                        border: "1px solid " + (active ? "var(--trust-tech)" : "var(--border-strong)"),
                        padding: "6px 12px", borderRadius: 999, fontSize: 12.5, fontWeight: 600,
                        cursor: "pointer", fontFamily: "inherit", fontVariantNumeric: "tabular-nums",
                        transition: "all 0.12s",
                        display: "inline-flex", alignItems: "center", gap: 6
                      }}>
                        <span>{p.l}</span>
                        <span style={{ opacity: 0.55 }}>·</span>
                        <span>{fmtUSD(p.v)}</span>
                      </button>);
                  })}
              </div>
            </div>
          </div>

          <div style={{
            borderTop: "1px solid var(--border-1)",
            padding: "14px 28px",
            background: "var(--tt-5)",
            display: "flex", alignItems: "center", justifyContent: "space-between",
            fontSize: 12.5, color: "var(--tt-60)"
          }}>
            <span style={{ display: "inline-flex", alignItems: "center", gap: 8 }}>
              <Icon name="info" size={13} color="var(--tt-60)" />
              {fmtUSD(sel.limit - initialDraw)} stays on your line for later.
            </span>
            <span className="tnum">
              Today: <span style={{ fontWeight: 700, color: "var(--trust-tech)" }}>{fmtUSD(initialDraw)}</span> · Available: <span style={{ fontWeight: 700, color: "var(--trust-tech)" }}>{fmtUSD(sel.limit - initialDraw)}</span>
            </span>
          </div>
        </div>

        {/* Footnote */}
        <div className="mt-6" style={{ marginTop: 18 }}>
          <Disclosure>
            Revenued's service provides for the purchase of future receivables and is not a loan. The factor rate is fixed at the time of agreement; total payback equals your draw multiplied by the factor rate. Final agreement on the next screen.
          </Disclosure>
        </div>

        {/* Action row */}
        <div style={{
          display: "flex", alignItems: "center", justifyContent: "space-between",
          marginTop: 28, gap: 16, flexWrap: "wrap"
        }}>
          <div style={{ display: "flex", alignItems: "center", gap: 14, fontSize: 13, color: "var(--tt-60)" }}>
            <span>Taking</span>
            <span className="tnum" style={{ fontWeight: 700, color: "var(--trust-tech)", fontSize: 14 }}>
              {fmtUSD(initialDraw)}
            </span>
            <span style={{ color: "var(--tt-40)" }}>of</span>
            <span className="tnum" style={{ fontWeight: 700, color: "var(--trust-tech)", fontSize: 14 }}>
              {fmtUSD(sel.limit)}
            </span>
            <span style={{ color: "var(--tt-40)" }}>·</span>
            <span>{sel.factor.toFixed(2)} factor</span>
            <span style={{ color: "var(--tt-40)" }}>·</span>
            <span>~{sel.days} days</span>
          </div>
          <Button variant="dark" size="lg" onClick={() => {
            setDraw && setDraw(initialDraw);
            onSelectOffer && onSelectOffer({
              limit: sel.limit, factor: sel.factor, days: sel.days,
              daily: sel.daily, apr: sel.apr, initialDraw
            });
            onContinue();
          }} iconAfter="arrow-right">
            Accept &amp; take {fmtUSD(initialDraw)}
          </Button>
        </div>
      </div>
    </div>);

};

// =====================================================================
// 8) FLEX LINE AGREEMENT
// =====================================================================
const ScreenAgreement = ({ tweaks, draw, selectedOffer, onSign, onBack }) => {
  const { factorRate } = tweaks;
  const terms = computeTerms(draw, factorRate);
  const spendingLimit = selectedOffer ? selectedOffer.limit : tweaks.offerAmount;
  const [signed, setSigned] = React.useState(false);
  const [confirmed, setConfirmed] = React.useState(false);

  return (
    <div className="cap fade-up">
      <div className="cap-shell">
        <div className="cap-header">
          <CapitalCobrand partnerName={tweaks.partnerName} attribution={tweaks.revenuedAttribution} />
          <button className="btn btn-text" onClick={onBack}><Icon name="arrow-left" size={14} /> Back</button>
        </div>

        <div style={{ marginBottom: 18 }}>
          <Eyebrow>Final step</Eyebrow>
          <h2 style={{ fontSize: 32, fontWeight: 700, letterSpacing: "-0.02em", margin: "10px 0 6px" }}>
            Sign your Flex Line agreement
          </h2>
          <p style={{ fontSize: 15, color: "var(--tt-60)", margin: 0, maxWidth: 540 }}>
            Look it over, check the boxes, and we'll move funds today.
          </p>
        </div>

        <div style={{ display: "grid", gridTemplateColumns: "1.4fr 1fr", gap: 20 }}>
          {/* Agreement preview */}
          <div className="card" style={{ padding: 0, overflow: "hidden" }}>
            <div style={{
              padding: "14px 22px", borderBottom: "1px solid var(--border-1)",
              display: "flex", alignItems: "center", justifyContent: "space-between",
              background: "var(--tt-5)"
            }}>
              <div style={{ fontSize: 12, fontWeight: 600, color: "var(--tt-80)" }}>
                Revenue Purchase &amp; Sale Agreement
              </div>
              <span className="pill pill-neutral">v2.14 · {new Date().toLocaleDateString("en-US", { month: "long", year: "numeric" })}</span>
            </div>
            <div style={{
              padding: "24px 28px", maxHeight: 460, overflow: "auto",
              fontFamily: "var(--font-primary)", fontSize: 13, lineHeight: 1.65, color: "var(--tt-80)"
            }}>
              <div style={{ fontWeight: 700, fontSize: 14, color: "var(--trust-tech)", marginBottom: 14 }}>1. Sale of Future Receivables</div>
              <p style={{ margin: "0 0 14px" }}>
                Acme Coffee Roasters LLC ("Seller") hereby sells, assigns, and transfers to Revenued LLC ("Purchaser") all rights, title, and interest in {fmtUSD(terms.payback)} of Seller's future receivables ("Purchased Amount") in exchange for an upfront purchase price of {fmtUSD(draw)} ("Purchase Price"). This Agreement is a sale of future receivables and is not a loan or extension of credit. There is no interest rate or finance charge.
              </p>
              <div style={{ fontWeight: 700, fontSize: 14, color: "var(--trust-tech)", marginBottom: 14 }}>2. Weekly Payment</div>
              <p style={{ margin: "0 0 14px" }}>
                Seller authorizes Purchaser to debit approximately {fmtUSD(terms.weekly)} from Seller's designated business deposit account once per week via ACH ("Weekly Payment"). Weekly Payment shall continue until the full Purchased Amount has been delivered. Weekly Payment may be reconciled based on actual receivables volume.
              </p>
              <div style={{ fontWeight: 700, fontSize: 14, color: "var(--trust-tech)", marginBottom: 14 }}>3. Subsequent Draws</div>
              <p style={{ margin: "0 0 14px" }}>
                Seller may, from time to time, request additional advances ("Cash Draws") against unused capacity in Seller's Flex Line, up to a maximum aggregate Purchased Amount of {fmtUSD(spendingLimit * factorRate)} at any time. Each Cash Draw shall be subject to the same Factor Rate of {factorRate.toFixed(2)} and shall be governed by the terms of this Agreement.
              </p>
              <div style={{ fontWeight: 700, fontSize: 14, color: "var(--trust-tech)", marginBottom: 14 }}>4. Early Payment Discount ("PayNow")</div>
              <p style={{ margin: "0 0 14px" }}>
                If Seller delivers the full Purchased Amount within 60 days of the date hereof, Purchaser shall apply a discount to the Purchased Amount in accordance with the schedule set forth in Schedule A. The applicable discount on the date of this Agreement is fifteen percent (15%).
              </p>
              <div style={{ fontWeight: 700, fontSize: 14, color: "var(--trust-tech)", marginBottom: 14 }}>5. No Personal Guarantee of Repayment</div>
              <p style={{ margin: "0 0 14px" }}>
                Seller's obligation under this Agreement is limited to the delivery of the Purchased Amount from future receivables. There is no personal guarantee of repayment in the event that Seller's business ceases to generate receivables due to ordinary-course business conditions. Seller does provide a personal guarantee of performance, attached as Exhibit B.
              </p>
              <div style={{ fontWeight: 700, fontSize: 14, color: "var(--trust-tech)", marginBottom: 14 }}>6. Representations and Warranties</div>
              <p style={{ margin: 0 }}>
                Seller represents that all information provided in the application is true and accurate, and that Seller has the authority to enter into this Agreement on behalf of the business.
              </p>
            </div>
            <div style={{ padding: "12px 22px", borderTop: "1px solid var(--border-1)", background: "var(--tt-5)", fontSize: 11.5, color: "var(--tt-60)", display: "flex", alignItems: "center", gap: 8 }}>
              <Icon name="scroll-text" size={13} /> 4 pages · scroll to read in full · or <a href="#" style={{ color: "var(--growth-galaxy)" }}>download a copy</a>
            </div>
          </div>

          {/* Terms snapshot + signature */}
          <div style={{ display: "flex", flexDirection: "column", gap: 16 }}>
            <div className="card card-pad" style={{ padding: 22 }}>
              <Eyebrow muted>Terms snapshot</Eyebrow>
              <div style={{ marginTop: 14, display: "flex", flexDirection: "column", gap: 4 }}>
                {[
                  ["Spending Limit", fmtUSD(spendingLimit)],
                  ["Initial Draw Amount", fmtUSD(draw)],
                  ["Purchase Price (you get)", fmtUSD(draw)],
                  ["Purchased Amount (you deliver)", fmtUSD(terms.payback)],
                  ["Factor rate", factorRate.toFixed(2)],
                  ["Weekly payment", "~" + fmtUSD(terms.weekly)],
                  ["Est. delivery period", "~" + terms.months + " months"]].
                  map(([k, v]) =>
                    <div key={k} style={{ display: "flex", justifyContent: "space-between", padding: "7px 0", borderBottom: "1px solid var(--border-1)", fontSize: 13 }}>
                      <span style={{ color: "var(--tt-60)" }}>{k}</span>
                      <span className="tnum" style={{ fontWeight: 600 }}>{v}</span>
                    </div>
                  )}
              </div>
            </div>

            <div className="card card-pad" style={{ padding: 22 }}>
              <Eyebrow muted>Sign &amp; accept</Eyebrow>
              <div style={{ marginTop: 16, display: "flex", flexDirection: "column", gap: 14 }}>
                <Check checked={signed} onChange={(e) => setSigned(e.target.checked)}>
                  I, <b>Sarah Chen</b>, acting as Owner of Acme Coffee Roasters LLC, have read and agree to the Revenue Purchase &amp; Sale Agreement.
                </Check>
                <Check checked={confirmed} onChange={(e) => setConfirmed(e.target.checked)}>
                  I authorize ACH debits from the connected business deposit account ····4391 in the amount of approximately {fmtUSD(terms.weekly)} each week.
                </Check>
              </div>
              <Button
                variant="dark"
                block
                size="lg"
                disabled={!signed || !confirmed}
                onClick={onSign}
                style={{ marginTop: 22 }}
                iconAfter="arrow-right">

                Sign and accept
              </Button>
              <div style={{ fontSize: 11, color: "var(--tt-60)", marginTop: 12, textAlign: "center" }}>
                Electronic signature is legally binding under the E-SIGN Act.
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>);

};

// =====================================================================
// 9) FUNDED / WELCOME
// =====================================================================
const ScreenFunded = ({ tweaks, draw, selectedOffer, onContinue }) => {
  // Count-up animation for the hero amount + staggered entrance for chrome.
  const [countUp, setCountUp] = React.useState(0);
  React.useEffect(() => {
    const duration = 1200;
    const start = performance.now();
    let raf;
    const tick = (now) => {
      const t = Math.min(1, (now - start) / duration);
      // ease-out cubic
      const eased = 1 - Math.pow(1 - t, 3);
      setCountUp(Math.round(draw * eased));
      if (t < 1) raf = requestAnimationFrame(tick);
    };
    raf = requestAnimationFrame(tick);
    return () => cancelAnimationFrame(raf);
  }, [draw]);

  return (
    <div className="cap fade-up" style={{
      minHeight: "100%",
      display: "grid",
      placeItems: "center",
      background: "linear-gradient(180deg, #FBFBF9 0%, #FBFBF9 40%, #F2F8F6 100%)"
    }}>
      <div className="cap-shell" style={{ width: "100%", padding: "60px 32px" }}>
        <div className="funded-stage" style={{ maxWidth: 720, margin: "0 auto", textAlign: "center", position: "relative" }}>
          {/* Decorative rings (static backdrop) */}
          <div style={{ position: "absolute", left: "50%", top: -20, transform: "translateX(-50%)", pointerEvents: "none" }}>
            <Rings size={500} palette="teal" />
          </div>

          {/* Ripple rings emanating from check badge */}
          <div className="funded-ripple-stage" aria-hidden="true">
            <span className="funded-ripple funded-ripple-1" />
            <span className="funded-ripple funded-ripple-2" />
            <span className="funded-ripple funded-ripple-3" />
          </div>

          {/* Confetti dots — a few subtle accents around the hero */}
          <div className="funded-confetti" aria-hidden="true">
            {[
              { x: -180, y: 10, d: 0, c: "var(--funding-pool)" },
              { x: 150, y: -30, d: 80, c: "var(--bright-opportunity)" },
              { x: -110, y: 130, d: 140, c: "var(--growth-galaxy)" },
              { x: 220, y: 100, d: 200, c: "var(--funding-pool)" },
              { x: -60, y: -40, d: 260, c: "var(--bright-opportunity)" },
              { x: 100, y: 180, d: 320, c: "var(--funding-pool)" }].
              map((p, i) =>
                <span key={i} className="funded-conf-dot" style={{
                  left: `calc(50% + ${p.x}px)`, top: `calc(50px + ${p.y}px)`,
                  background: p.c,
                  animationDelay: `${p.d}ms`
                }} />
              )}
          </div>

          <div style={{ position: "relative", zIndex: 1 }}>
            <div className="funded-check" style={{
              width: 84, height: 84, borderRadius: 22,
              background: "var(--funding-pool)",
              display: "grid", placeItems: "center",
              margin: "0 auto 28px",
              boxShadow: "0 14px 44px rgba(4,196,158,0.45), 0 0 0 0 rgba(4,196,158,0.35)"
            }}>
              <Icon name="check" size={42} color="var(--trust-tech)" strokeWidth={3} />
            </div>

            <div className="funded-fade" style={{ animationDelay: "0.35s" }}>
              <Eyebrow>Your Flex Line is active</Eyebrow>
            </div>

            <h1 className="funded-fade" style={{
              animationDelay: "0.45s",
              fontSize: 56, fontWeight: 700, letterSpacing: "-0.025em",
              margin: "16px 0 12px", lineHeight: 1.05,
              fontVariantNumeric: "tabular-nums"
            }}>
              {fmtUSD(countUp)} is on the way.
            </h1>
            <p className="funded-fade" style={{
              animationDelay: "0.55s",
              fontSize: 17, color: "var(--tt-60)", margin: "0 0 36px", lineHeight: 1.5
            }}>
              Funds typically arrive in your Chase ····4391 account within 24 hours. We'll text Sarah when it lands.
            </p>

            <div style={{ display: "grid", gridTemplateColumns: "repeat(3, 1fr)", gap: 14, marginBottom: 36 }}>
              {[
                { ic: "send", t: "Funds in transit", d: "ACH initiated · arrives next biz day" },
                { ic: "calendar-clock", t: "Weekly payment starts", d: "First debit: " + new Date(Date.now() + 86400000 * 10).toLocaleDateString("en-US", { weekday: "long", month: "short", day: "numeric" }) },
                { ic: "trending-up", t: fmtUSD(Math.max(0, (selectedOffer ? selectedOffer.limit : tweaks.offerAmount) - draw)) + " still on your line", d: "Draw it anytime you need it" }].
                map((p, i) =>
                  <div key={i} className="funded-fade" style={{
                    animationDelay: `${0.75 + i * 0.12}s`,
                    background: "rgba(255,255,255,0.7)",
                    border: "1px solid var(--border-1)",
                    borderRadius: 14, padding: 18, textAlign: "left",
                    backdropFilter: "blur(8px)"
                  }}>
                    <div style={{ width: 30, height: 30, borderRadius: 8, background: "var(--fp-10)", color: "var(--fp-100)", display: "grid", placeItems: "center", marginBottom: 10 }}>
                      <Icon name={p.ic} size={16} />
                    </div>
                    <div style={{ fontSize: 13.5, fontWeight: 600, color: "var(--trust-tech)" }}>{p.t}</div>
                    <div style={{ fontSize: 12, color: "var(--tt-60)", marginTop: 4 }}>{p.d}</div>
                  </div>
                )}
            </div>

            <div className="funded-fade" style={{ animationDelay: "1.2s" }}>
              <Button variant="dark" size="lg" onClick={onContinue} iconAfter="arrow-right">
                Go to my dashboard
              </Button>
            </div>
          </div>
        </div>
      </div>

      <style>{`
        @keyframes funded-pop {
          0%   { transform: scale(0.4); opacity: 0; }
          55%  { transform: scale(1.18); opacity: 1; }
          80%  { transform: scale(0.96); }
          100% { transform: scale(1); }
        }
        @keyframes funded-glow {
          0%, 100% { box-shadow: 0 14px 44px rgba(4,196,158,0.40), 0 0 0 0 rgba(4,196,158,0); }
          50%      { box-shadow: 0 18px 56px rgba(4,196,158,0.55), 0 0 0 12px rgba(4,196,158,0.10); }
        }
        @keyframes funded-fade-up {
          0%   { transform: translateY(14px); opacity: 0; }
          100% { transform: translateY(0); opacity: 1; }
        }
        @keyframes funded-ripple-anim {
          0%   { transform: translate(-50%, -50%) scale(0.4); opacity: 0.55; }
          100% { transform: translate(-50%, -50%) scale(3.2); opacity: 0; }
        }
        @keyframes funded-conf {
          0%   { transform: translate(-50%, -50%) scale(0); opacity: 0; }
          25%  { transform: translate(-50%, -50%) scale(1.2); opacity: 1; }
          100% { transform: translate(-50%, -50%) scale(1) translateY(40px); opacity: 0; }
        }
        .funded-check {
          animation:
            funded-pop 0.7s cubic-bezier(0.34, 1.56, 0.64, 1) both,
            funded-glow 2.4s ease-in-out 0.8s infinite;
        }
        .funded-fade {
          animation: funded-fade-up 0.6s cubic-bezier(0.2, 0, 0, 1) both;
        }
        .funded-ripple-stage {
          position: absolute;
          top: 42px; left: 50%;
          width: 0; height: 0;
          pointer-events: none;
          z-index: 0;
        }
        .funded-ripple {
          position: absolute;
          top: 0; left: 0;
          width: 90px; height: 90px;
          margin-left: -45px; margin-top: -45px;
          border: 2px solid var(--funding-pool);
          border-radius: 22px;
          opacity: 0;
          transform: translate(-50%, -50%) scale(0.4);
          animation: funded-ripple-anim 2.2s cubic-bezier(0.2, 0, 0, 1) 0.2s infinite;
        }
        .funded-ripple-2 { animation-delay: 0.9s; border-color: var(--bright-opportunity); }
        .funded-ripple-3 { animation-delay: 1.55s; border-color: var(--funding-pool); }
        .funded-confetti {
          position: absolute; inset: 0; pointer-events: none; z-index: 0;
        }
        .funded-conf-dot {
          position: absolute;
          width: 10px; height: 10px;
          border-radius: 3px;
          opacity: 0;
          transform: translate(-50%, -50%) scale(0);
          animation: funded-conf 1.4s cubic-bezier(0.2, 0, 0, 1) both;
        }
      `}</style>
    </div>);

};

Object.assign(window, {
  ScreenOffer, ScreenAmount, ScreenPlaid, ScreenBusiness, ScreenOwner,
  ScreenReview, ScreenDecision, ScreenAgreement, ScreenFunded,
  fmtUSD, computeTerms
});