// Fictional internally-consistent business data for RBI mockup states.
// Atlas Bakery LLC — Maria Kowalski — Brooklyn, NY
// Chase Business (Plaid connected) · applied to Revenued May 10, 2026 · declined

const RBI_PROFILES = {
  declined: {
    state: "declined",
    business: {
      name: "Atlas Bakery LLC",
      owner: "Maria Kowalski",
      city: "Brooklyn, NY",
      industry: "Commercial bakery · NAICS 311812",
      yearsOpen: 6,
      bank: "Chase Business ····4391",
    },
    decline: {
      product: "Flex line — $40,000 requested",
      daysAgo: 12,
      primaryReason: "Cash buffer below 30 days for 3 consecutive months",
    },
    score: {
      value: 740,
      max: 999,
      band: "Fair",
      trend30: -3,
      trend90: -8,
      sentence: "Your business credit sits in the middle of the pack for bakeries your size — slipping slightly over the last 60 days.",
      drivers: [
        { name: "Payment history", weight: 35, value: 78, band: "Good", note: "On-time with all tradelines except one supplier 14d late in March." },
        { name: "Credit utilization", weight: 25, value: 41, band: "Fair", note: "Business card at 64% of limit. Pulling under 30% would help." },
        { name: "Cash flow stability", weight: 20, value: 38, band: "Watch", note: "Buffer trending down 3 months. The largest single factor pulling this score." },
        { name: "Account age", weight: 10, value: 82, band: "Strong", note: "6 years of continuous SBFE-reported activity." },
        { name: "Public records", weight: 10, value: 95, band: "Strong", note: "No liens, judgments, or UCC filings." },
      ],
    },
    cashflow: {
      headline: "Tight month. Watch your buffer.",
      narrative: "Revenue came in at $84,200 — within $2K of your six-month average. Spending ran 6% higher than last month, mostly a pull-ahead flour order. The real story: your cash buffer dropped from 38 days to 26, declining three months running. That's the single thing pulling your score and your eligibility down.",
      metrics: [
        { label: "Revenue · 30d", value: "$84,200", delta: "−2.1% vs avg", tone: "neutral" },
        { label: "Spending · 30d", value: "$79,180", delta: "+6.0% MoM", tone: "warn" },
        { label: "Cash buffer", value: "26 days", delta: "−12 days · 3 mo ↓", tone: "warn" },
        { label: "Net margin · 30d", value: "5.9%", delta: "−1.4 pts MoM", tone: "warn" },
      ],
      anomalies: [
        { kind: "warn", label: "5 NSF / overdraft events", detail: "$142 in fees · all on Chase ····4391", action: "fees" },
        { kind: "warn", label: "Greenpoint Hotels paid 14 days late", detail: "$11,800 invoice · your largest wholesale buyer", action: "ar" },
        { kind: "info", label: "Card processing fees up 31%", detail: "vs. bakeries your size · Stripe at 3.1% effective", action: "fees" },
      ],
    },
    eligibility: [
      {
        id: "revenued-mca",
        funder: "Revenued",
        funderType: "direct",
        product: "Flex line — Merchant Cash Advance",
        amount: "$25,000",
        amountRange: "up to",
        status: "not-recommended",
        rate: "factor 1.32 · ~21% effective",
        term: "9-month payback",
        note: "Available, but we don't think you should take it right now. The daily payback (~2.4% of deposits) would push your buffer below 20 days inside the first month.",
      },
      {
        id: "fl-capital-plus",
        funder: "Bluevine",
        funderType: "financelogic",
        product: "Working capital term loan",
        amount: "$15,000",
        amountRange: "up to",
        status: "available",
        rate: "12.4% APR",
        term: "18-month term · fixed monthly",
        note: "Smaller, lower-stakes. Fixed payment of $912/mo is easier to plan around than a percentage of deposits.",
      },
      {
        id: "fl-equipment",
        funder: "Currency Finance",
        funderType: "financelogic",
        product: "Equipment financing",
        amount: "$35,000",
        amountRange: "up to",
        status: "qualify-soon",
        rate: "9.8% APR (indicative)",
        term: "Secured by equipment",
        note: "You'd qualify in roughly 60 days if your buffer holds above 35 days. Lowest-cost path if you're replacing the proofer.",
      },
      {
        id: "sba-microloan",
        funder: "Pursuit Lending (SBA microloan)",
        funderType: "financelogic",
        product: "SBA Community Advantage",
        amount: "$50,000",
        amountRange: "up to",
        status: "available",
        rate: "8.25% APR",
        term: "5-year term · 4–6 week close",
        note: "Cheapest capital on this page. Trade-off is the timeline — not useful if you need money this week.",
      },
    ],
    moves: [
      {
        title: "Zero overdrafts for 60 days",
        impact: "Moves your eligibility up one tier",
        detail: "You've had 5 overdrafts in the last 30 days — $142 in fees. Every funder on this page weighs NSF events heavily. A clean 60-day window is the single fastest signal you can send.",
        confidence: "high",
      },
      {
        title: "Hold cash buffer above 45 days for one quarter",
        impact: "Would change the Revenued decline picture",
        detail: "Your buffer trending below 30 days is the main driver of why we declined the $40K request. Buffer is the strongest predictor we have of payback risk. 45+ days for 90 days would put you back in the approve bucket on the same product.",
        confidence: "high",
      },
      {
        title: "Switch to a business bank with lower fees",
        impact: "~$3,000/yr saved · improves cash buffer",
        detail: "You're paying $340/mo in account, wire, and overdraft fees on Chase Business. Bakeries your size typically pay around $90. Mercury, Relay, or Bluevine Business Checking would cut this to under $30/mo. The savings rebuild your buffer faster than almost any revenue change.",
        confidence: "med",
      },
    ],
  },

  improving: {
    state: "improving",
    business: {
      name: "Atlas Bakery LLC",
      owner: "Maria Kowalski",
      city: "Brooklyn, NY",
      industry: "Commercial bakery · NAICS 311812",
      yearsOpen: 6,
      bank: "Chase Business ····4391",
    },
    decline: {
      product: "Flex line — $40,000 requested",
      daysAgo: 67,
      primaryReason: "Cash buffer below 30 days · since reversed",
    },
    score: {
      value: 888,
      max: 999,
      band: "Strong",
      trend30: 18,
      trend90: 45,
      sentence: "Your business credit is in the top third for bakeries your size — climbing steadily for three months.",
      drivers: [
        { name: "Payment history", weight: 35, value: 88, band: "Strong", note: "Clean six months. Two suppliers reporting early payment." },
        { name: "Credit utilization", weight: 25, value: 71, band: "Strong", note: "Business card down to 28% utilization." },
        { name: "Cash flow stability", weight: 20, value: 76, band: "Strong", note: "Buffer rebuilt to 47 days. Three months of upward trend." },
        { name: "Account age", weight: 10, value: 82, band: "Strong", note: "Same as before — 6 years of clean history." },
        { name: "Public records", weight: 10, value: 95, band: "Strong", note: "Still clean." },
      ],
    },
    cashflow: {
      headline: "Strong month. Momentum is real.",
      narrative: "Revenue hit $98,400 — your best month of the year, up 11% MoM. The wholesale side did most of the work: Greenpoint Hotels and the new Williamsburg account added $22K combined, both paid on time. Spending stayed disciplined, so your cash buffer climbed from 31 days to 47.",
      metrics: [
        { label: "Revenue · 30d", value: "$98,400", delta: "+11.4% MoM", tone: "good" },
        { label: "Spending · 30d", value: "$74,100", delta: "−2.3% MoM", tone: "good" },
        { label: "Cash buffer", value: "47 days", delta: "+16 days · 3 mo ↑", tone: "good" },
        { label: "Net margin · 30d", value: "12.8%", delta: "+4.5 pts MoM", tone: "good" },
      ],
      anomalies: [
        { kind: "good", label: "Wholesale receivables up 22%", detail: "Best month since opening · 4 new accounts active", action: "ar" },
        { kind: "good", label: "Zero NSF events for 47 days", detail: "Last overdraft Apr 5 · streak in progress", action: "fees" },
        { kind: "info", label: "Stripe processing fees still high", detail: "3.1% effective vs ~2.6% peers · room to negotiate", action: "fees" },
      ],
    },
    eligibility: [
      {
        id: "revenued-mca",
        funder: "Revenued",
        funderType: "direct",
        product: "Flex line — Merchant Cash Advance",
        amount: "$45,000",
        amountRange: "up to",
        status: "recommended",
        rate: "factor 1.26 · ~17% effective",
        term: "9-month payback · draw on demand",
        note: "Better terms than you'd have gotten 60 days ago. Best fit if you need flexibility — pull what you need, when you need it.",
      },
      {
        id: "fl-termcap",
        funder: "Funding Circle",
        funderType: "financelogic",
        product: "Working capital term loan",
        amount: "$80,000",
        amountRange: "up to",
        status: "available",
        rate: "8.4% APR",
        term: "36-month term · fixed monthly",
        note: "Lower rate than the flex line, but committed monthly payment. Best fit if you have a specific use of funds and a payback plan.",
      },
      {
        id: "fl-equipment",
        funder: "Currency Finance",
        funderType: "financelogic",
        product: "Equipment financing",
        amount: "$35,000",
        amountRange: "up to",
        status: "available",
        rate: "7.9% APR",
        term: "Secured by equipment · 5 year",
        note: "Lowest rate on this page. Tied to a specific piece of equipment — replacement proofer, mixer, or oven.",
      },
      {
        id: "sba-7a",
        funder: "Live Oak Bank (SBA 7(a))",
        funderType: "financelogic",
        product: "SBA 7(a) loan",
        amount: "$150,000",
        amountRange: "up to",
        status: "available",
        rate: "Prime + 2.75% · ~11.25%",
        term: "10-year term · 6–8 week close",
        note: "Biggest amount, slowest close. Worth it if you're considering an expansion — second location, large equipment purchase.",
      },
    ],
    moves: [
      {
        title: "Renegotiate Stripe processing",
        impact: "~$2,400/yr saved at current volume",
        detail: "You're at 3.1% effective. With $1.1M in card volume, dropping to 2.6% is worth roughly $200/month. Stripe will negotiate above $1M annual — ask for interchange-plus pricing.",
        confidence: "high",
      },
      {
        title: "Lock in 60 more days of clean cash flow",
        impact: "Unlocks SBA 7(a) at $200K+ tier",
        detail: "You're 47 days into the streak. Hitting 90 days of buffer above 45 + zero NSF would move you from the basic SBA tier to the better one. The rate stays similar but the cap moves up significantly.",
        confidence: "high",
      },
      {
        title: "Start formalizing AR aging",
        impact: "Lower-cost financing options open up",
        detail: "Once you've got 6 months of clean wholesale receivables, invoice financing becomes a real option — typically 1–2% per month against invoiced amounts, no fixed payback. Won't be needed now, but worth setting up the data trail.",
        confidence: "med",
      },
    ],
  },

  reeligible: {
    state: "reeligible",
    business: {
      name: "Atlas Bakery LLC",
      owner: "Maria Kowalski",
      city: "Brooklyn, NY",
      industry: "Commercial bakery · NAICS 311812",
      yearsOpen: 6,
      bank: "Mercury Business ····2210",
    },
    decline: {
      product: "Flex line — $40,000 requested",
      daysAgo: 142,
      primaryReason: "Cash buffer · fully reversed",
    },
    score: {
      value: 917,
      max: 999,
      band: "Strong",
      trend30: 12,
      trend90: 73,
      sentence: "Your business credit is in the top quartile for bakeries your size — and Revenued would now approve the same application we declined in January.",
      drivers: [
        { name: "Payment history", weight: 35, value: 92, band: "Strong", note: "Eight months perfectly clean across all tradelines." },
        { name: "Credit utilization", weight: 25, value: 84, band: "Strong", note: "Business card paid down to 12% utilization." },
        { name: "Cash flow stability", weight: 20, value: 88, band: "Strong", note: "Buffer at 62 days. Five months of upward trend." },
        { name: "Account age", weight: 10, value: 84, band: "Strong", note: "6 years + Mercury account now seasoned." },
        { name: "Public records", weight: 10, value: 95, band: "Strong", note: "Still clean." },
      ],
    },
    cashflow: {
      headline: "You'd be approved today.",
      narrative: "Revenue hit $112,500 — a new high. Buffer is 62 days. Five months without an overdraft. The $40K flex line you applied for in January would clear automatically against our current credit policy. Structurally, this is a different business than the one we saw five months ago.",
      metrics: [
        { label: "Revenue · 30d", value: "$112,500", delta: "+14.3% MoM", tone: "good" },
        { label: "Spending · 30d", value: "$78,200", delta: "+5.5% MoM", tone: "neutral" },
        { label: "Cash buffer", value: "62 days", delta: "+15 days · 5 mo ↑", tone: "good" },
        { label: "Net margin · 30d", value: "13.6%", delta: "+0.8 pts MoM", tone: "good" },
      ],
      anomalies: [
        { kind: "good", label: "5 months no overdrafts", detail: "Mercury account · zero NSF since switch", action: "fees" },
        { kind: "good", label: "Williamsburg café renewed at higher SKU mix", detail: "Recurring $14K/mo · 36-month agreement", action: "ar" },
        { kind: "info", label: "Bank fees down to $28/mo", detail: "From $340/mo on Chase · $3,700/yr savings realized", action: "fees" },
      ],
    },
    eligibility: [
      {
        id: "revenued-reapproved",
        funder: "Revenued",
        funderType: "direct",
        product: "Flex line — re-eligible (the one you applied for)",
        amount: "$45,000",
        amountRange: "approved up to",
        status: "reapproved",
        rate: "factor 1.24 · ~16% effective",
        term: "9-month payback · draw on demand",
        note: "Same product, better terms. You can accept the offer in two clicks — funds settle next business day. No re-application needed.",
      },
      {
        id: "revenued-line-increase",
        funder: "Revenued",
        funderType: "direct",
        product: "Flex line — increased cap",
        amount: "$75,000",
        amountRange: "up to",
        status: "available",
        rate: "factor 1.28 · ~18% effective",
        term: "12-month payback",
        note: "Bigger ceiling. Worth considering if the Williamsburg expansion is on the table.",
      },
      {
        id: "fl-termcap-pro",
        funder: "Funding Circle",
        funderType: "financelogic",
        product: "Working capital term loan",
        amount: "$120,000",
        amountRange: "up to",
        status: "available",
        rate: "7.4% APR",
        term: "48-month term",
        note: "Cheaper than our own product. We'll tell you that. Best fit if you have a defined use and 36+ months of runway.",
      },
      {
        id: "sba-7a-large",
        funder: "Live Oak Bank (SBA 7(a))",
        funderType: "financelogic",
        product: "SBA 7(a) loan",
        amount: "$250,000",
        amountRange: "up to",
        status: "available",
        rate: "Prime + 2.5% · ~11.0%",
        term: "10-year term",
        note: "Now in the larger SBA tier. Right tool if you're thinking second location.",
      },
    ],
    moves: [
      {
        title: "Keep doing what you're doing",
        impact: "Maintain the trajectory",
        detail: "You're in a structurally different position than five months ago. The Mercury switch, the wholesale-account additions, and the consistent buffer are the three things that compounded. None of them are easy to undo accidentally — but stay aware.",
        confidence: "high",
      },
      {
        title: "Build a 6-month emergency reserve before expansion",
        impact: "Unlocks the SBA 7(a) larger tier on better terms",
        detail: "If a second location is on the table, lenders will look at your reserves alongside the line. Getting to 6 months of operating expenses in cash (currently at 2) before applying meaningfully improves the rate you'd be offered.",
        confidence: "high",
      },
    ],
  },
};

window.RBI_PROFILES = RBI_PROFILES;

// ────────────────────────────────────────────────────────────────────────────
// Shared scenario state. The Home overview's "Scenario" tweak writes here;
// Cash Flow and Industry Insights read from here so the story stays in sync
// when the user switches scenarios on any page. Persisted via localStorage
// so it survives a hard refresh.
window.RBI_STATE = (function () {
  let cur = "declined";
  try {
    const saved = localStorage.getItem("rbi-scenario");
    if (saved === "declined" || saved === "improving" || saved === "reeligible") cur = saved;
  } catch (e) { }
  const subs = new Set();
  return {
    get: function () { return cur; },
    set: function (s) {
      if (!RBI_PROFILES[s] || s === cur) return;
      cur = s;
      try { localStorage.setItem("rbi-scenario", s); } catch (e) { }
      subs.forEach(function (fn) { fn(s); });
    },
    subscribe: function (fn) { subs.add(fn); return function () { subs.delete(fn); }; }
  };
})();

// React hook for any component to subscribe to scenario changes.
window.useScenario = function () {
  const [s, setS] = React.useState(window.RBI_STATE.get());
  React.useEffect(function () { return window.RBI_STATE.subscribe(setS); }, []);
  return s;
};
