// ============================================================
// Flex Line Dashboard — the BD-pitch "money screen"
// Includes: summary, active draws, payment calendar (m/w/list),
// transaction history, Cash Draw + PayNow full-screen takeovers.
//
// Terminology (per Smeet):
//  - "Spending Limit" (not "Total Flex Line")
//  - "Spending Availability" (not "Available to draw")
//  - "PayNow Balance" (not "Balance owed")
//  - "Weekly payment" (not "Daily remittance")
//  - "PayNow" (one word) is the early-payment feature
//  - Multiple draws supported; each inherits the parent Flex Line terms
// ============================================================

const TODAY = new Date(2026, 4, 14); // May 14, 2026

// --- Mock state: one draw on a single Flex Line ---------------
// (Initial draw amount + factor are overridden at render time when the user
//  picks an offer on the Decision page — see FlexDashboard below.)
const DRAWS = [
{ id: 1, date: new Date(2026, 1, 20), amount: 25000, factorRate: 1.30, label: "Initial draw" }];


const TOTAL_PAYBACK = DRAWS.reduce((s, d) => s + d.amount * d.factorRate, 0);
const TOTAL_DRAWN = DRAWS.reduce((s, d) => s + d.amount, 0);

const DASH_STATE = {
  spendingLimit: 75000,
  totalDrawn: TOTAL_DRAWN,
  spendingAvailability: 75000 - TOTAL_DRAWN,
  totalPayback: TOTAL_PAYBACK,
  paidSoFar: 5800,
  payNowBalance: TOTAL_PAYBACK - 5800,
  weeklyPayment: 650,
  factorRate: 1.30,
  earlyPayoffDiscountRate: 0.07, // applied to PayNow Balance
  fundingAccount: "Chase ····4391"
};

// First payment landed the Friday after the first draw
const FIRST_PAYMENT_DATE = new Date(2026, 1, 27); // Fri Feb 27 2026

// --------------------------------------------------------------
// Build a weekly-payment + single-draw transaction history.
// Newest first. Parameters are pulled from the selected offer at render time.
// --------------------------------------------------------------
function buildTransactions({ drawAmount, factor, weeklyPayment, drawDate }) {
  const events = [];
  events.push({
    date: drawDate,
    type: "Draw", desc: "Draw · " + DRAWS[0].label,
    amount: drawAmount, sign: "+", icon: "arrow-down-left"
  });
  let cursor = new Date(FIRST_PAYMENT_DATE);
  let payNowInserted = false;
  while (cursor < TODAY) {
    events.push({
      date: new Date(cursor),
      type: "Payment", desc: "Weekly payment",
      amount: Math.round(weeklyPayment), sign: "−", icon: "arrow-up-right"
    });
    // Insert a PayNow event at one point
    if (cursor.getMonth() === 2 && cursor.getDate() < 14 && !payNowInserted) {
      events.push({
        date: new Date(cursor),
        type: "PayNow", desc: "PayNow · partial payment",
        amount: 1500, sign: "−", icon: "fast-forward"
      });
      payNowInserted = true;
    }
    cursor.setDate(cursor.getDate() + 7);
  }
  // Compute running balance going forward
  let running = 0;
  for (let i = 0; i < events.length; i++) {
    if (events[i].type === "Draw") running += events[i].amount * factor;else
    running -= events[i].amount;
    events[i].balance = Math.max(0, Math.round(running));
  }
  return events.reverse();
}

// =====================================================================
// Payment Calendar — weekly cadence
// =====================================================================
const PaymentCalendar = ({ weeklyPayment = DASH_STATE.weeklyPayment }) => {
  const [view, setView] = React.useState("month");
  const [month, setMonth] = React.useState(new Date(2026, 4, 1));
  const [popover, setPopover] = React.useState(null);

  // Map of payment dates → info. Weekly payments fall on Fridays.
  const paymentDates = React.useMemo(() => {
    const map = new Map();
    // Past payments
    let c = new Date(FIRST_PAYMENT_DATE);
    while (c < TODAY) {
      map.set(c.toDateString(), {
        amount: Math.round(weeklyPayment),
        status: "paid"
      });
      c.setDate(c.getDate() + 7);
    }
    // Today's marker (find the closest Friday to TODAY)
    const todayFriday = new Date(TODAY);
    while (todayFriday.getDay() !== 5) todayFriday.setDate(todayFriday.getDate() + 1);
    map.set(todayFriday.toDateString(), {
      amount: Math.round(weeklyPayment), status: "upcoming"
    });
    // Future upcoming + projected
    let f = new Date(todayFriday);
    f.setDate(f.getDate() + 7);
    for (let i = 0; i < 26; i++) {
      map.set(f.toDateString(), {
        amount: Math.round(weeklyPayment),
        status: i < 10 ? "upcoming" : "projected"
      });
      f.setDate(f.getDate() + 7);
    }
    return map;
  }, [weeklyPayment]);

  const navMonth = (delta) => {
    const n = new Date(month);
    n.setMonth(n.getMonth() + delta);
    setMonth(n);
  };

  const renderMonth = () => {
    const start = new Date(month.getFullYear(), month.getMonth(), 1);
    const startDow = start.getDay();
    const daysInMonth = new Date(month.getFullYear(), month.getMonth() + 1, 0).getDate();
    const cells = [];
    for (let i = 0; i < startDow; i++) cells.push(null);
    for (let d = 1; d <= daysInMonth; d++) cells.push(new Date(month.getFullYear(), month.getMonth(), d));
    while (cells.length % 7 !== 0) cells.push(null);

    return (
      <div>
        <div style={{ display: "grid", gridTemplateColumns: "repeat(7, 1fr)", gap: 4, marginBottom: 6 }}>
          {["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"].map((d) =>
          <div key={d} style={{ fontSize: 10, fontWeight: 700, letterSpacing: "0.10em", color: "var(--tt-60)", textTransform: "uppercase", textAlign: "center", padding: "8px 0" }}>{d}</div>
          )}
        </div>
        <div style={{ display: "grid", gridTemplateColumns: "repeat(7, 1fr)", gap: 4 }}>
          {cells.map((c, i) => {
            if (!c) return <div key={i} style={{ aspectRatio: "1 / 0.85" }} />;
            const info = paymentDates.get(c.toDateString());
            const isToday = c.toDateString() === TODAY.toDateString();
            const isWeekend = c.getDay() === 0 || c.getDay() === 6;
            let bg = "var(--tt-5)";
            let color = "var(--tt-80)";
            let border = "1px solid transparent";
            if (info?.status === "paid") {bg = "var(--fp-10)";color = "#075c3e";} else
            if (info?.status === "upcoming") {bg = "#fff";color = "var(--trust-tech)";border = "1px solid var(--gg-20)";} else
            if (info?.status === "projected") {bg = "transparent";color = "var(--tt-40)";border = "1px dashed var(--gg-20)";}
            if (isToday && !info) {bg = "var(--growth-galaxy)";color = "#fff";}
            if (isWeekend && !info && !isToday) {color = "var(--tt-40)";bg = "transparent";}

            return (
              <button
                key={i}
                onMouseEnter={(e) => {
                  if (!info && !isToday) return;
                  const rect = e.currentTarget.getBoundingClientRect();
                  const parent = e.currentTarget.closest(".cap-shell, .cap").getBoundingClientRect();
                  setPopover({
                    date: c, info: info || { amount: null, status: "today" },
                    x: rect.left - parent.left + rect.width / 2,
                    y: rect.top - parent.top - 8
                  });
                }}
                onMouseLeave={() => setPopover(null)}
                style={{
                  aspectRatio: "1 / 0.85", background: bg, color, border,
                  borderRadius: 8, display: "flex", flexDirection: "column",
                  alignItems: "flex-start", justifyContent: "space-between",
                  padding: "8px 10px", cursor: info || isToday ? "pointer" : "default",
                  font: "inherit", transition: "all 140ms"
                }}>
                <span style={{
                  fontSize: 12.5,
                  fontWeight: isToday ? 700 : 600,
                  fontVariantNumeric: "tabular-nums"
                }}>{c.getDate()}</span>
                {info &&
                <span style={{
                  fontSize: 10, fontWeight: 700,
                  fontVariantNumeric: "tabular-nums",
                  opacity: info.status === "projected" ? 0.5 : 0.9
                }}>${info.amount}</span>
                }
                {isToday && !info &&
                <span style={{ fontSize: 9, fontWeight: 700, letterSpacing: "0.10em", textTransform: "uppercase" }}>Today</span>
                }
              </button>);

          })}
        </div>

        {popover &&
        <div style={{
          position: "absolute", left: popover.x, top: popover.y,
          transform: "translate(-50%, -100%)",
          background: "var(--trust-tech)", color: "#fff",
          padding: "10px 14px", borderRadius: 8,
          boxShadow: "0 10px 30px rgba(0,18,43,0.30)",
          fontSize: 12, whiteSpace: "nowrap", zIndex: 5, pointerEvents: "none"
        }}>
            <div style={{ fontWeight: 700 }}>
              {popover.info.status === "paid" ? "Paid" :
            popover.info.status === "today" ? "Today" :
            popover.info.status === "upcoming" ? "Upcoming payment" : "Projected payment"}
              {popover.info.amount && ` · $${popover.info.amount}`}
            </div>
            <div style={{ opacity: 0.7, fontSize: 11 }}>
              {popover.date.toLocaleDateString("en-US", { weekday: "long", month: "long", day: "numeric" })}
            </div>
          </div>
        }
      </div>);

  };

  const renderWeek = () => {
    const start = new Date(TODAY);
    start.setDate(start.getDate() - start.getDay());
    const days = [];
    for (let i = 0; i < 7; i++) {
      const d = new Date(start);
      d.setDate(start.getDate() + i);
      days.push(d);
    }
    return (
      <div style={{ display: "grid", gridTemplateColumns: "repeat(7, 1fr)", gap: 8 }}>
        {days.map((c, i) => {
          const info = paymentDates.get(c.toDateString());
          const isToday = c.toDateString() === TODAY.toDateString();
          return (
            <div key={i} style={{
              padding: 16, borderRadius: 12,
              background: isToday ? "var(--growth-galaxy)" : info?.status === "paid" ? "var(--fp-10)" : info ? "#fff" : "var(--tt-5)",
              color: isToday ? "#fff" : "var(--trust-tech)",
              border: info?.status === "upcoming" && !isToday ? "1px solid var(--gg-20)" : "1px solid transparent",
              minHeight: 130, display: "flex", flexDirection: "column", justifyContent: "space-between"
            }}>
              <div>
                <div style={{ fontSize: 10.5, fontWeight: 700, letterSpacing: "0.10em", textTransform: "uppercase", opacity: 0.7 }}>
                  {c.toLocaleDateString("en-US", { weekday: "short" })}
                </div>
                <div style={{ fontSize: 28, fontWeight: 700, letterSpacing: "-0.02em", marginTop: 4 }}>{c.getDate()}</div>
              </div>
              {info ?
              <div>
                  <div style={{ fontSize: 12, opacity: 0.85 }}>
                    {info.status === "paid" ? "Paid" : info.status === "upcoming" ? "Upcoming" : "Projected"}
                  </div>
                  <div style={{ fontSize: 17, fontWeight: 700, fontVariantNumeric: "tabular-nums", marginTop: 2 }}>${info.amount}</div>
                </div> :
              isToday ? <div style={{ fontSize: 11, opacity: 0.85 }}>Today</div> :
              <div style={{ fontSize: 11, color: "var(--tt-40)" }}>—</div>
              }
            </div>);

        })}
      </div>);

  };

  const renderList = () => {
    const entries = [];
    paymentDates.forEach((info, key) => entries.push({ date: new Date(key), info }));
    entries.sort((a, b) => b.date - a.date);
    const recent = entries.slice(0, 14);
    return (
      <div style={{ borderTop: "1px solid var(--border-1)" }}>
        {recent.map((e, i) =>
        <div key={i} style={{
          display: "grid", gridTemplateColumns: "120px 1fr 100px 100px",
          padding: "12px 4px", borderBottom: "1px solid var(--border-1)",
          alignItems: "center", fontSize: 13
        }}>
            <span style={{ fontWeight: 600, color: "var(--trust-tech)" }}>
              {e.date.toLocaleDateString("en-US", { month: "short", day: "numeric" })}
            </span>
            <span style={{ color: "var(--tt-60)" }}>
              {e.date.toLocaleDateString("en-US", { weekday: "long" })} · Weekly payment
            </span>
            <span className={"pill " + (
          e.info.status === "paid" ? "pill-teal" :
          e.info.status === "upcoming" ? "pill-neutral" : "pill-neutral")
          } style={{ justifySelf: "start" }}>
              {e.info.status}
            </span>
            <span className="tnum" style={{ fontWeight: 700, textAlign: "right" }}>${e.info.amount}</span>
          </div>
        )}
      </div>);

  };

  return (
    <div className="card card-pad" style={{ position: "relative" }}>
      <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between", marginBottom: 20 }}>
        <div>
          <Eyebrow>Payment calendar</Eyebrow>
          <div style={{ fontSize: 18, fontWeight: 700, marginTop: 6 }}>
            Weekly payment · ${Math.round(weeklyPayment)} every Friday
          </div>
        </div>

        <div style={{ display: "flex", gap: 12, alignItems: "center" }}>
          {view === "month" &&
          <div style={{ display: "flex", alignItems: "center", gap: 4 }}>
              <button onClick={() => navMonth(-1)} className="mv-icon-btn" style={{ width: 28, height: 28 }}>
                <Icon name="chevron-left" size={14} />
              </button>
              <div style={{ fontSize: 13, fontWeight: 600, padding: "0 8px", minWidth: 130, textAlign: "center" }}>
                {month.toLocaleDateString("en-US", { month: "long", year: "numeric" })}
              </div>
              <button onClick={() => navMonth(1)} className="mv-icon-btn" style={{ width: 28, height: 28 }}>
                <Icon name="chevron-right" size={14} />
              </button>
            </div>
          }
          <div style={{ display: "flex", background: "var(--tt-5)", padding: 3, borderRadius: 8 }}>
            {[{ id: "month", l: "Month" }, { id: "week", l: "Week" }, { id: "list", l: "List" }].map((v) =>
            <button key={v.id} onClick={() => setView(v.id)} style={{
              background: view === v.id ? "#fff" : "transparent",
              boxShadow: view === v.id ? "0 1px 3px rgba(0,18,43,0.08)" : "none",
              padding: "5px 12px", borderRadius: 6, border: "none",
              fontSize: 12, fontWeight: 600, cursor: "pointer",
              color: view === v.id ? "var(--trust-tech)" : "var(--tt-60)",
              fontFamily: "inherit"
            }}>{v.l}</button>
            )}
          </div>
        </div>
      </div>

      {view === "month" && renderMonth()}
      {view === "week" && renderWeek()}
      {view === "list" && renderList()}

      <div style={{ display: "flex", gap: 16, marginTop: 18, paddingTop: 14, borderTop: "1px solid var(--border-1)", fontSize: 11, color: "var(--tt-60)", flexWrap: "wrap" }}>
        <span style={{ display: "flex", alignItems: "center", gap: 6 }}>
          <span style={{ width: 12, height: 12, background: "var(--fp-10)", borderRadius: 3 }} /> Paid
        </span>
        <span style={{ display: "flex", alignItems: "center", gap: 6 }}>
          <span style={{ width: 12, height: 12, background: "var(--growth-galaxy)", borderRadius: 3 }} /> Today
        </span>
        <span style={{ display: "flex", alignItems: "center", gap: 6 }}>
          <span style={{ width: 12, height: 12, background: "#fff", border: "1px solid var(--gg-20)", borderRadius: 3 }} /> Upcoming
        </span>
        <span style={{ display: "flex", alignItems: "center", gap: 6 }}>
          <span style={{ width: 12, height: 12, background: "transparent", border: "1px dashed var(--gg-20)", borderRadius: 3 }} /> Projected
        </span>
      </div>
    </div>);

};

// =====================================================================
// Transaction History
// =====================================================================
const TransactionHistory = ({
  drawAmount = DRAWS[0].amount,
  factor = DASH_STATE.factorRate,
  weeklyPayment = DASH_STATE.weeklyPayment,
  drawDate = DRAWS[0].date
}) => {
  const [filter, setFilter] = React.useState("All");
  const txs = React.useMemo(
    () => buildTransactions({ drawAmount, factor, weeklyPayment, drawDate }),
    [drawAmount, factor, weeklyPayment, drawDate]
  );
  const filtered = txs.filter((t) =>
  filter === "All" ? true :
  filter === "Draws" ? t.type === "Draw" :
  filter === "Payments" ? t.type === "Payment" :
  filter === "PayNow" ? t.type === "PayNow" : true
  );
  const limited = filtered.slice(0, 12);

  return (
    <div className="card" style={{ padding: 0, overflow: "hidden" }}>
      <div style={{ padding: "20px 24px 16px", display: "flex", alignItems: "center", justifyContent: "space-between" }}>
        <div>
          <Eyebrow>Transaction history</Eyebrow>
          <div style={{ fontSize: 18, fontWeight: 700, marginTop: 6 }}>Recent activity</div>
        </div>
        <div style={{ display: "flex", gap: 6 }}>
          {["All", "Draws", "Payments", "PayNow"].map((f) =>
          <button key={f} onClick={() => setFilter(f)} style={{
            background: filter === f ? "var(--trust-tech)" : "transparent",
            color: filter === f ? "#fff" : "var(--tt-60)",
            border: "1px solid " + (filter === f ? "var(--trust-tech)" : "var(--border-1)"),
            padding: "5px 12px", borderRadius: 999, fontSize: 12, fontWeight: 600,
            cursor: "pointer", fontFamily: "inherit"
          }}>{f}</button>
          )}
        </div>
      </div>

      <div className="tx-header" style={{
        padding: "10px 24px", background: "var(--tt-5)",
        borderTop: "1px solid var(--border-1)", borderBottom: "1px solid var(--border-1)",
        display: "grid", gridTemplateColumns: "100px 1fr 110px 100px 120px",
        fontSize: 10, fontWeight: 700, letterSpacing: "0.10em", textTransform: "uppercase", color: "var(--tt-60)"
      }}>
        <span>Date</span><span>Description</span><span>Type</span>
        <span style={{ textAlign: "right" }}>Amount</span>
        <span style={{ textAlign: "right" }}>Balance</span>
      </div>

      {limited.map((t, i) => {
        const isDraw = t.type === "Draw";
        const isPayNow = t.type === "PayNow";
        return (
          <div key={i} className="tx-row" style={{
            padding: "12px 24px",
            display: "grid", gridTemplateColumns: "100px 1fr 110px 100px 120px",
            alignItems: "center", fontSize: 13,
            borderBottom: "1px solid var(--border-1)"
          }}>
            <span className="tx-date" style={{ color: "var(--tt-80)", fontWeight: 500 }}>
              {t.date.toLocaleDateString("en-US", { month: "short", day: "numeric" })}
            </span>
            <div className="tx-desc" style={{ display: "flex", alignItems: "center", gap: 10 }}>
              <div style={{
                width: 28, height: 28, borderRadius: 7,
                background: isDraw ? "var(--gg-10)" : isPayNow ? "var(--fp-10)" : "var(--tt-5)",
                color: isDraw ? "var(--growth-galaxy)" : isPayNow ? "var(--fp-100)" : "var(--tt-60)",
                display: "grid", placeItems: "center", flexShrink: 0
              }}>
                <Icon name={t.icon} size={14} />
              </div>
              <span style={{ color: "var(--trust-tech)", fontWeight: 500 }}>{t.desc}</span>
            </div>
            <span className="tx-type">
              <span className={"pill " + (isDraw ? "pill-blue" : isPayNow ? "pill-teal" : "pill-neutral")}>{t.type}</span>
            </span>
            <span className="tx-amount tnum" style={{
              fontWeight: 600, textAlign: "right",
              color: isDraw ? "var(--growth-galaxy)" : "var(--tt-80)"
            }}>
              {t.sign}${t.amount.toLocaleString()}
            </span>
            <span className="tx-balance tnum" style={{ fontWeight: 600, textAlign: "right", color: "var(--tt-60)" }}>
              ${t.balance.toLocaleString()}
            </span>
          </div>);

      })}

      <div style={{ padding: "12px 24px", textAlign: "center" }}>
        <a href="#" style={{ fontSize: 12.5, fontWeight: 600 }}>View all {txs.length} transactions →</a>
      </div>
    </div>);

};

// =====================================================================
// CASH DRAW takeover (3 steps)
// =====================================================================
const CashDrawTakeover = ({ tweaks, onClose, onConfirm }) => {
  const [step, setStep] = React.useState(1);
  const available = DASH_STATE.spendingAvailability;
  const [amount, setAmount] = React.useState(15000);
  const [signed, setSigned] = React.useState(false);
  const newPayback = DASH_STATE.totalPayback + amount * tweaks.factorRate;
  const newPayNowBalance = DASH_STATE.payNowBalance + amount * tweaks.factorRate;
  const newWeekly = Math.round(newPayNowBalance / 42); // soft estimate

  return (
    <div className="cap-overlay">
      <div className="cap">
        <div className="cap-shell" style={{ maxWidth: 1080 }}>
          <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between", paddingTop: 4, marginBottom: 28 }}>
            <CapitalCobrand partnerName={tweaks.partnerName} attribution={tweaks.revenuedAttribution} />
            <button className="btn btn-text" onClick={onClose}>
              <Icon name="x" size={14} /> Cancel
            </button>
          </div>

          {step === 1 &&
          <>
              <Steps step={1} total={3} labels={["Amount", "Review", "Done"]} />

              <div className="mt-6" style={{ marginTop: 28, display: "grid", gridTemplateColumns: "1.3fr 1fr", gap: 28 }}>
                <div className="card card-pad">
                  <Eyebrow>Take a cash draw</Eyebrow>
                  <h2 style={{ fontSize: 28, fontWeight: 700, letterSpacing: "-0.015em", margin: "10px 0 24px" }}>
                    How much do you want to pull?
                  </h2>
                  <div style={{ fontFamily: "var(--font-primary)", fontWeight: 700, fontSize: 64, letterSpacing: "-0.025em", lineHeight: 1, margin: "0 0 8px" }} className="tnum">
                    {fmtUSD(amount)}
                  </div>
                  <div style={{ fontSize: 13, color: "var(--tt-60)", marginBottom: 24 }}>
                    {fmtUSD(available)} available on your line · This draw inherits your Flex Line terms ({tweaks.factorRate.toFixed(2)}× factor rate)
                  </div>

                  <MoneySlider value={amount} min={1000} max={available} step={500} onChange={setAmount} />

                  <div style={{ display: "flex", gap: 8, marginTop: 22, flexWrap: "wrap" }}>
                    {[5000, 10000, 25000, available].map((v) =>
                  <button key={v} onClick={() => setAmount(v)} style={{
                    background: amount === v ? "var(--trust-tech)" : "#fff",
                    color: amount === v ? "#fff" : "var(--trust-tech)",
                    border: "1px solid " + (amount === v ? "var(--trust-tech)" : "var(--border-strong)"),
                    padding: "8px 14px", borderRadius: 999, fontSize: 13, fontWeight: 600,
                    cursor: "pointer", fontFamily: "inherit", fontVariantNumeric: "tabular-nums"
                  }}>{v === available ? "Max " + fmtUSD(v) : fmtUSD(v)}</button>
                  )}
                  </div>
                </div>

                <div className="card card-pad" style={{ background: "var(--trust-tech)", color: "#fff", border: "none", position: "relative", overflow: "hidden" }}>
                  <div style={{ position: "absolute", right: -50, bottom: -50, opacity: 0.55 }}>
                    <Rings size={240} palette="teal" />
                  </div>
                  <div style={{ position: "relative", zIndex: 1 }}>
                    <Eyebrow muted style={{ color: "var(--funding-pool)" }}>What changes</Eyebrow>
                    <div style={{ marginTop: 18, display: "flex", flexDirection: "column", gap: 14 }}>
                      <div style={{ display: "flex", justifyContent: "space-between", paddingBottom: 12, borderBottom: "1px solid rgba(255,255,255,0.10)" }}>
                        <div>
                          <div style={{ fontSize: 11, color: "rgba(255,255,255,0.55)", textTransform: "uppercase", letterSpacing: "0.10em" }}>PayNow Balance</div>
                          <div className="tnum" style={{ fontSize: 13, color: "rgba(255,255,255,0.65)", marginTop: 4 }}>{fmtUSD(DASH_STATE.payNowBalance)} <span style={{ opacity: 0.5 }}>→</span></div>
                        </div>
                        <div className="tnum" style={{ fontSize: 22, fontWeight: 700, alignSelf: "flex-end" }}>{fmtUSD(newPayNowBalance)}</div>
                      </div>
                      <div style={{ display: "flex", justifyContent: "space-between", paddingBottom: 12, borderBottom: "1px solid rgba(255,255,255,0.10)" }}>
                        <div>
                          <div style={{ fontSize: 11, color: "rgba(255,255,255,0.55)", textTransform: "uppercase", letterSpacing: "0.10em" }}>Weekly payment</div>
                          <div className="tnum" style={{ fontSize: 13, color: "rgba(255,255,255,0.65)", marginTop: 4 }}>${DASH_STATE.weeklyPayment} <span style={{ opacity: 0.5 }}>→</span></div>
                        </div>
                        <div className="tnum" style={{ fontSize: 22, fontWeight: 700, alignSelf: "flex-end" }}>~${newWeekly}</div>
                      </div>
                      <div style={{ display: "flex", justifyContent: "space-between" }}>
                        <div>
                          <div style={{ fontSize: 11, color: "rgba(255,255,255,0.55)", textTransform: "uppercase", letterSpacing: "0.10em" }}>Active draws</div>
                          <div className="tnum" style={{ fontSize: 13, color: "rgba(255,255,255,0.65)", marginTop: 4 }}>{DRAWS.length} <span style={{ opacity: 0.5 }}>→</span></div>
                        </div>
                        <div className="tnum" style={{ fontSize: 22, fontWeight: 700, alignSelf: "flex-end" }}>{DRAWS.length + 1}</div>
                      </div>
                    </div>
                  </div>
                </div>
              </div>

              <div style={{ display: "flex", justifyContent: "flex-end", marginTop: 32 }}>
                <Button variant="dark" size="lg" onClick={() => setStep(2)} iconAfter="arrow-right">
                  Continue with {fmtUSD(amount)}
                </Button>
              </div>
            </>
          }

          {step === 2 &&
          <>
              <Steps step={2} total={3} labels={["Amount", "Review", "Done"]} />
              <div className="mt-6" style={{ marginTop: 28 }}>
                <Eyebrow>Confirm cash draw</Eyebrow>
                <h2 style={{ fontSize: 32, fontWeight: 700, letterSpacing: "-0.02em", margin: "10px 0 6px" }}>Review and sign</h2>
                <p style={{ fontSize: 15, color: "var(--tt-60)", margin: "0 0 24px", maxWidth: 540 }}>
                  Each draw on your Flex Line inherits the parent agreement — same factor rate, same payback structure.
                </p>

                <div className="card card-pad" style={{ maxWidth: 720 }}>
                  <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: "4px 32px" }}>
                    {[
                  ["You receive", fmtUSD(amount), "var(--growth-galaxy)"],
                  ["Added to payback", fmtUSD(amount * tweaks.factorRate), null],
                  ["Factor rate", tweaks.factorRate.toFixed(2), null],
                  ["New PayNow Balance", fmtUSD(newPayNowBalance), null],
                  ["New weekly payment", "~$" + newWeekly, null],
                  ["Funded to", DASH_STATE.fundingAccount, null]].
                  map(([k, v, c]) =>
                  <div key={k} 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 className="tnum" style={{ fontWeight: 700, color: c || "var(--trust-tech)" }}>{v}</span>
                      </div>
                  )}
                  </div>

                  <div style={{ marginTop: 22 }}>
                    <Check checked={signed} onChange={(e) => setSigned(e.target.checked)}>
                      I, <b>Sarah Chen</b>, authorize this cash draw and confirm it's governed by my existing Flex Line agreement.
                    </Check>
                  </div>
                  <div style={{ marginTop: 16 }}>
                    <Disclosure>
                      Revenued's service provides for the purchase of future receivables and is not a loan. Each draw inherits the parent agreement's terms.
                    </Disclosure>
                  </div>
                </div>

                <div style={{ display: "flex", justifyContent: "space-between", marginTop: 32 }}>
                  <button className="btn btn-text" onClick={() => setStep(1)}>
                    <Icon name="arrow-left" size={14} /> Back
                  </button>
                  <Button variant="dark" size="lg" disabled={!signed} onClick={() => setStep(3)} iconAfter="arrow-right">
                    Sign and confirm draw
                  </Button>
                </div>
              </div>
            </>
          }

          {step === 3 &&
          <div style={{ display: "grid", placeItems: "center", minHeight: "70vh" }}>
              <div style={{ maxWidth: 540, textAlign: "center", position: "relative" }}>
                <div style={{ position: "absolute", left: "50%", top: -40, transform: "translateX(-50%)" }}>
                  <Rings size={420} palette="teal" />
                </div>
                <div style={{ position: "relative", zIndex: 1 }}>
                  <div style={{
                  width: 64, height: 64, borderRadius: 18,
                  background: "var(--funding-pool)", color: "var(--trust-tech)",
                  display: "grid", placeItems: "center", margin: "0 auto 24px",
                  boxShadow: "0 12px 40px rgba(4,196,158,0.40)"
                }}>
                    <Icon name="check" size={32} strokeWidth={3} />
                  </div>
                  <Eyebrow>Draw confirmed</Eyebrow>
                  <h2 style={{ fontSize: 40, fontWeight: 700, letterSpacing: "-0.02em", margin: "14px 0 12px", lineHeight: 1.1 }}>
                    {fmtUSD(amount)} is on the way.
                  </h2>
                  <p style={{ fontSize: 15, color: "var(--tt-60)", margin: "0 0 32px", lineHeight: 1.55 }}>
                    Funds typically arrive in your {DASH_STATE.fundingAccount} account within 24 hours.
                  </p>
                  <Button variant="dark" size="lg" onClick={onConfirm} iconAfter="arrow-right">
                    Back to dashboard
                  </Button>
                </div>
              </div>
            </div>
          }
        </div>
      </div>
    </div>);

};

// =====================================================================
// PAYNOW takeover — user enters any amount
// =====================================================================
const PayNowTakeover = ({ tweaks, onClose, onConfirm }) => {
  const [step, setStep] = React.useState(1);
  const [signed, setSigned] = React.useState(false);
  const [amount, setAmount] = React.useState(5000); // user-chosen, defaults to a partial payment
  const balance = DASH_STATE.payNowBalance;
  const isFullPayoff = amount >= balance;
  // Early-payoff discount only applies on a full payoff
  const discount = isFullPayoff ? Math.round(balance * DASH_STATE.earlyPayoffDiscountRate) : 0;
  const willDebit = Math.max(0, amount - discount);
  const remainingAfter = Math.max(0, balance - amount);

  return (
    <div className="cap-overlay">
      <div className="cap">
        <div className="cap-shell" style={{ maxWidth: 1080 }}>
          <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between", paddingTop: 4, marginBottom: 28 }}>
            <CapitalCobrand partnerName={tweaks.partnerName} attribution={tweaks.revenuedAttribution} />
            <button className="btn btn-text" onClick={onClose}>
              <Icon name="x" size={14} /> Cancel
            </button>
          </div>

          {step === 1 &&
          <>
              <Eyebrow>PayNow</Eyebrow>
              <h2 style={{ fontSize: 32, fontWeight: 700, letterSpacing: "-0.02em", margin: "10px 0 6px" }}>
                Make an extra payment toward your balance
              </h2>
              <p style={{ fontSize: 15, color: "var(--tt-60)", margin: "0 0 28px", maxWidth: 580 }}>
                Pay any amount, anytime. Pay it all off and we'll knock {Math.round(DASH_STATE.earlyPayoffDiscountRate * 100)}% off your remaining balance.
              </p>

              <div style={{ display: "grid", gridTemplateColumns: "1.2fr 1fr", gap: 20 }}>
                {/* Amount input card */}
                <div className="card card-pad">
                  <Eyebrow>How much do you want to pay?</Eyebrow>
                  <div style={{ fontFamily: "var(--font-primary)", fontWeight: 700, fontSize: 64, letterSpacing: "-0.025em", lineHeight: 1, margin: "14px 0 8px" }} className="tnum">
                    {fmtUSD(amount)}
                  </div>
                  <div style={{ fontSize: 13, color: "var(--tt-60)", marginBottom: 24 }}>
                    Your PayNow Balance is {fmtUSD(balance)}. Pay any amount up to the full balance.
                  </div>

                  <MoneySlider value={amount} min={500} max={balance} step={100} onChange={setAmount} />

                  <div style={{ display: "flex", gap: 8, marginTop: 22, flexWrap: "wrap" }}>
                    {[2500, 5000, 10000, balance].map((v) =>
                  <button key={v} onClick={() => setAmount(v)} style={{
                    background: amount === v ? "var(--trust-tech)" : "#fff",
                    color: amount === v ? "#fff" : "var(--trust-tech)",
                    border: "1px solid " + (amount === v ? "var(--trust-tech)" : "var(--border-strong)"),
                    padding: "8px 14px", borderRadius: 999, fontSize: 13, fontWeight: 600,
                    cursor: "pointer", fontFamily: "inherit", fontVariantNumeric: "tabular-nums"
                  }}>
                        {v === balance ? "Pay off · " + fmtUSD(v) : fmtUSD(v)}
                      </button>
                  )}
                  </div>

                  {isFullPayoff &&
                <div style={{
                  marginTop: 20, padding: "12px 14px",
                  background: "var(--fp-5)", border: "1px solid var(--fp-20)",
                  borderRadius: 10, display: "flex", gap: 10, alignItems: "center"
                }}>
                      <Icon name="sparkle" size={16} color="var(--fp-100)" />
                      <div style={{ fontSize: 13, color: "#075c3e" }}>
                        Paying it all off — we'll apply a <b>{Math.round(DASH_STATE.earlyPayoffDiscountRate * 100)}% discount</b> ({fmtUSD(discount)}) to your balance.
                      </div>
                    </div>
                }
                </div>

                {/* Side card */}
                <div className="card card-pad" style={{
                background: isFullPayoff ?
                "linear-gradient(135deg, var(--funding-pool) 0%, #048468 100%)" :
                "var(--trust-tech)",
                color: "#fff", border: "none", position: "relative", overflow: "hidden"
              }}>
                  <div style={{ position: "absolute", right: -40, top: -40, opacity: 0.6 }}>
                    <Rings size={280} palette={isFullPayoff ? "light" : "teal"} />
                  </div>
                  <div style={{ position: "relative", zIndex: 1 }}>
                    <Eyebrow muted style={{ color: isFullPayoff ? "rgba(255,255,255,0.85)" : "var(--funding-pool)" }}>
                      {isFullPayoff ? "You'll save" : "Payment summary"}
                    </Eyebrow>
                    <div style={{ fontFamily: "var(--font-primary)", fontWeight: 700, fontSize: isFullPayoff ? 64 : 48, letterSpacing: "-0.03em", lineHeight: 1, margin: "12px 0 8px" }} className="tnum">
                      {isFullPayoff ? fmtUSD(discount) : fmtUSD(willDebit)}
                    </div>
                    <div style={{ fontSize: 14, color: "rgba(255,255,255,0.78)", marginBottom: 22 }}>
                      {isFullPayoff ?
                    "off your PayNow Balance — debits today." :
                    "debits today. Your weekly payment continues until the balance is delivered."}
                    </div>
                    <div style={{ display: "flex", flexDirection: "column", gap: 0, paddingTop: 14, borderTop: "1px solid rgba(255,255,255,0.15)" }}>
                      {[
                    ["PayNow Balance today", fmtUSD(balance)],
                    ["You pay", fmtUSD(amount)],
                    isFullPayoff ? ["Early payoff discount", "−" + fmtUSD(discount)] : null,
                    ["Debits from your account", fmtUSD(willDebit)],
                    ["Balance after", fmtUSD(remainingAfter)]].
                    filter(Boolean).map(([k, v], i, arr) =>
                    <div key={i} style={{ display: "flex", justifyContent: "space-between", padding: "9px 0", borderBottom: i < arr.length - 1 ? "1px solid rgba(255,255,255,0.10)" : "none", fontSize: 13 }}>
                          <span style={{ color: "rgba(255,255,255,0.7)" }}>{k}</span>
                          <span className="tnum" style={{ fontWeight: 700, fontSize: 13.5 }}>{v}</span>
                        </div>
                    )}
                    </div>
                  </div>
                </div>
              </div>

              <div className="mt-6" style={{ marginTop: 20 }}>
                <Disclosure>
                  Revenued's service provides for the purchase of future receivables and is not a loan. The PayNow discount applies only on a full payoff of the outstanding balance.
                </Disclosure>
              </div>

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

          {step === 2 &&
          <>
              <Eyebrow>Confirm PayNow</Eyebrow>
              <h2 style={{ fontSize: 32, fontWeight: 700, letterSpacing: "-0.02em", margin: "10px 0 6px" }}>
                Authorize {fmtUSD(willDebit)} payment
              </h2>
              <p style={{ fontSize: 15, color: "var(--tt-60)", margin: "0 0 28px", maxWidth: 580 }}>
                {isFullPayoff ?
              "After this, your balance is zero and your full Spending Limit is back." :
              "Your weekly payment continues on Fridays until the rest of the balance is delivered."}
              </p>

              <div className="card card-pad" style={{ maxWidth: 720 }}>
                <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: "4px 32px" }}>
                  {[
                ["You pay", fmtUSD(amount), null],
                isFullPayoff ? ["You save", fmtUSD(discount), "var(--growth-galaxy)"] : null,
                ["Debits from", DASH_STATE.fundingAccount, null],
                ["Debit date", "Tomorrow", null],
                ["Balance after", fmtUSD(remainingAfter), "var(--funding-pool)"]].
                filter(Boolean).map(([k, v, c]) =>
                <div key={k} 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 className="tnum" style={{ fontWeight: 700, color: c || "var(--trust-tech)" }}>{v}</span>
                    </div>
                )}
                </div>

                <div style={{ marginTop: 22 }}>
                  <Check checked={signed} onChange={(e) => setSigned(e.target.checked)}>
                    I, <b>Sarah Chen</b>, authorize Revenued to debit {fmtUSD(willDebit)} from {DASH_STATE.fundingAccount} toward my PayNow Balance.
                  </Check>
                </div>
              </div>

              <div style={{ display: "flex", justifyContent: "space-between", marginTop: 32 }}>
                <button className="btn btn-text" onClick={() => setStep(1)}>
                  <Icon name="arrow-left" size={14} /> Back
                </button>
                <Button variant="dark" size="lg" disabled={!signed} onClick={() => setStep(3)} iconAfter="arrow-right">
                  Confirm payment
                </Button>
              </div>
            </>
          }

          {step === 3 &&
          <div style={{ display: "grid", placeItems: "center", minHeight: "70vh" }}>
              <div style={{ maxWidth: 540, textAlign: "center", position: "relative" }}>
                <div style={{ position: "absolute", left: "50%", top: -40, transform: "translateX(-50%)" }}>
                  <Rings size={420} palette="teal" />
                </div>
                <div style={{ position: "relative", zIndex: 1 }}>
                  <div style={{
                  width: 64, height: 64, borderRadius: 18,
                  background: "var(--funding-pool)", color: "var(--trust-tech)",
                  display: "grid", placeItems: "center", margin: "0 auto 24px",
                  boxShadow: "0 12px 40px rgba(4,196,158,0.40)"
                }}>
                    <Icon name="check" size={32} strokeWidth={3} />
                  </div>
                  <Eyebrow>Payment scheduled</Eyebrow>
                  <h2 style={{ fontSize: 36, fontWeight: 700, letterSpacing: "-0.02em", margin: "14px 0 12px", lineHeight: 1.1 }}>
                    {isFullPayoff ?
                  `You just saved ${fmtUSD(discount)}.` :
                  `${fmtUSD(willDebit)} payment scheduled.`}
                  </h2>
                  <p style={{ fontSize: 15, color: "var(--tt-60)", margin: "0 0 32px", lineHeight: 1.55 }}>
                    {fmtUSD(willDebit)} debits from {DASH_STATE.fundingAccount} tomorrow.{" "}
                    {isFullPayoff ?
                  `Once it clears, your ${fmtUSD(DASH_STATE.spendingLimit)} Spending Limit is fully restored.` :
                  `Remaining balance: ${fmtUSD(remainingAfter)}.`}
                  </p>
                  <Button variant="dark" size="lg" onClick={onConfirm} iconAfter="arrow-right">
                    Back to dashboard
                  </Button>
                </div>
              </div>
            </div>
          }
        </div>
      </div>
    </div>);

};

// =====================================================================
// FLEX LINE DASHBOARD
// =====================================================================
// =====================================================================
// FLEX LINE DASHBOARD
// =====================================================================
const UtilizationDonut = ({ drawn, limit }) => {
  const targetPct = limit > 0 ? Math.min(1, drawn / limit) : 0;
  const r = 62;
  const c = 2 * Math.PI * r;

  // Animated percentage — eases in on mount and whenever the target changes.
  const [animPct, setAnimPct] = React.useState(0);
  React.useEffect(() => {
    const start = performance.now();
    const startVal = animPct;
    const duration = 900;
    let raf;
    const tick = (now) => {
      const t = Math.min(1, (now - start) / duration);
      const eased = 1 - Math.pow(1 - t, 3);
      setAnimPct(startVal + (targetPct - startVal) * eased);
      if (t < 1) raf = requestAnimationFrame(tick);
    };
    raf = requestAnimationFrame(tick);
    return () => cancelAnimationFrame(raf);
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [targetPct]);

  return (
    <div style={{ position: "relative", width: 160, height: 160, flexShrink: 0 }}>
      <svg width="160" height="160" viewBox="0 0 160 160" style={{ display: "block" }}>
        <circle cx="80" cy="80" r={r} fill="none" stroke="rgba(255,255,255,0.12)" strokeWidth="14" />
        <circle
          cx="80" cy="80" r={r}
          fill="none"
          stroke="var(--funding-pool)"
          strokeWidth="14"
          strokeLinecap="round"
          strokeDasharray={`${animPct * c} ${c}`}
          transform="rotate(-90 80 80)" />
      </svg>
      <div style={{
        position: "absolute", inset: 0,
        display: "flex", flexDirection: "column", alignItems: "center", justifyContent: "center"
      }}>
        <div style={{ fontSize: 10, fontWeight: 700, letterSpacing: "0.14em", color: "rgba(255,255,255,0.55)", textTransform: "uppercase" }}>Used</div>
        <div className="tnum" style={{ fontFamily: "var(--font-primary)", fontWeight: 700, fontSize: 34, color: "#fff", letterSpacing: "-0.025em", lineHeight: 1, marginTop: 4 }}>
          {Math.round(animPct * 100)}%
        </div>
        <div className="tnum" style={{ fontSize: 11, color: "rgba(255,255,255,0.55)", marginTop: 4, whiteSpace: "nowrap" }}>
          ${Math.round(drawn / 1000)}K of ${Math.round(limit / 1000)}K
        </div>
      </div>
    </div>);
};

// Last 12 months ending in May 2026; small dip in Nov from a late payment.
const SCORE_HISTORY = [
{ month: "Jun", score: 690 },
{ month: "Jul", score: 694 },
{ month: "Aug", score: 698 },
{ month: "Sep", score: 703 },
{ month: "Oct", score: 709 },
{ month: "Nov", score: 712 },
{ month: "Dec", score: 705 },
{ month: "Jan", score: 712 },
{ month: "Feb", score: 718 },
{ month: "Mar", score: 722 },
{ month: "Apr", score: 725 },
{ month: "May", score: 728 }];


const REPORTING_HISTORY = [
{ month: "Jun", status: "ontime" },
{ month: "Jul", status: "ontime" },
{ month: "Aug", status: "ontime" },
{ month: "Sep", status: "ontime" },
{ month: "Oct", status: "ontime" },
{ month: "Nov", status: "late" },
{ month: "Dec", status: "ontime" },
{ month: "Jan", status: "ontime" },
{ month: "Feb", status: "ontime" },
{ month: "Mar", status: "ontime" },
{ month: "Apr", status: "ontime" },
{ month: "May", status: "ontime" }];


const ScoreSparkline = ({ data, height = 80 }) => {
  const scores = data.map((d) => d.score);
  const minRaw = Math.min(...scores);
  const maxRaw = Math.max(...scores);
  const min = minRaw - 8;
  const max = maxRaw + 8;
  const W = 320; // natural pixel coords — SVG scales uniformly to container
  const H = height;
  const PX = 6;
  const PY = 6;
  const chartH = H - 12;
  const points = data.map((d, i) => {
    const x = PX + i / (data.length - 1) * (W - 2 * PX);
    const y = PY + (1 - (d.score - min) / (max - min)) * (chartH - PY);
    return { x, y, ...d };
  });
  const pathD = points.map((p, i) => i === 0 ? `M ${p.x} ${p.y}` : `L ${p.x} ${p.y}`).join(" ");
  const areaD = `${pathD} L ${points[points.length - 1].x} ${chartH} L ${points[0].x} ${chartH} Z`;
  const last = points[points.length - 1];
  const lateIdx = data.findIndex((d, i) => i > 0 && d.score < data[i - 1].score);
  const late = lateIdx >= 0 ? points[lateIdx] : null;
  const gradId = "score-spark-grad";

  return (
    <svg width="100%" height={H} viewBox={`0 0 ${W} ${H}`} preserveAspectRatio="xMidYMid meet" style={{ display: "block", overflow: "visible" }}>
      <defs>
        <linearGradient id={gradId} x1="0" y1="0" x2="0" y2="1">
          <stop offset="0%" stopColor="var(--growth-galaxy)" stopOpacity="0.22" />
          <stop offset="100%" stopColor="var(--growth-galaxy)" stopOpacity="0" />
        </linearGradient>
      </defs>
      <path d={areaD} fill={`url(#${gradId})`} />
      <path d={pathD} fill="none" stroke="var(--growth-galaxy)" strokeWidth="1.6" strokeLinejoin="round" strokeLinecap="round" vectorEffect="non-scaling-stroke" />
      {late &&
      <circle cx={late.x} cy={late.y} r="3.5" fill="#e0a85f" stroke="#fff" strokeWidth="1.5" vectorEffect="non-scaling-stroke" />
      }
      <circle cx={last.x} cy={last.y} r="4" fill="#fff" stroke="var(--growth-galaxy)" strokeWidth="2" vectorEffect="non-scaling-stroke" />
    </svg>);
};

const ReportingGrid = ({ data }) => {
  const colors = {
    ontime: "var(--funding-pool)",
    late: "#e0a85f",
    bounced: "#e07a5f"
  };
  const labels = {
    ontime: "On-time payment",
    late: "Late payment",
    bounced: "Bounced/unpaid"
  };
  return (
    <div style={{ display: "grid", gridTemplateColumns: "repeat(12, 1fr)", gap: 4 }}>
      {data.map((m, i) =>
      <div key={i} style={{ display: "flex", flexDirection: "column", alignItems: "center", gap: 4 }}>
          <div
          title={`${m.month}: ${labels[m.status] || "Not reported"}`}
          style={{
            width: "100%", aspectRatio: "1",
            borderRadius: 5,
            background: colors[m.status] || "var(--tt-10)",
            opacity: m.status ? 1 : 0.4,
            boxShadow: m.status === "late" ? "0 0 0 1px rgba(224,168,95,0.4)" : "none"
          }} />
          <div style={{ fontSize: 9.5, color: "var(--tt-60)", fontWeight: 600, letterSpacing: "0.02em" }}>{m.month}</div>
        </div>)}
    </div>);
};

const SBFEDashboardCard = () => {
  const current = SCORE_HISTORY[SCORE_HISTORY.length - 1].score;
  const yearAgo = SCORE_HISTORY[0].score;
  const delta = current - yearAgo;
  const tier = current >= 740 ? { label: "Excellent", color: "#0040BA" } :
  current >= 670 ? { label: "Good", color: "var(--funding-pool)" } :
  current >= 580 ? { label: "Fair", color: "#e0a85f" } :
  { label: "Poor", color: "#e07a5f" };
  const ontimeCount = REPORTING_HISTORY.filter((r) => r.status === "ontime").length;

  return (
    <div className="card" style={{ marginBottom: 20, padding: 0, overflow: "hidden", position: "relative" }}>
      {/* Header row */}
      <div style={{
        display: "flex", alignItems: "flex-start", justifyContent: "space-between",
        padding: "22px 26px 18px",
        borderBottom: "1px solid var(--border-1)"
      }}>
        <div>
          <Eyebrow>Business credit · SBFE</Eyebrow>
          <div style={{ fontSize: 20, fontWeight: 700, marginTop: 6, letterSpacing: "-0.01em", color: "var(--trust-tech)" }}>
            Your SBFE Credit Score
          </div>
          <div style={{ fontSize: 12.5, color: "var(--tt-60)", marginTop: 4 }}>
            Reported by your Revenued Flex Line · last pulled {TODAY.toLocaleDateString("en-US", { month: "long", day: "numeric", year: "numeric" })}
          </div>
        </div>
        <button className="btn btn-text" style={{ color: "var(--tt-60)" }}>
          <Icon name="refresh-ccw" size={13} /> Refresh
        </button>
      </div>

      {/* Body grid */}
      <div style={{ display: "grid", gridTemplateColumns: "minmax(0, 0.7fr) minmax(0, 1.1fr) minmax(0, 1.4fr)", padding: "24px 26px", gap: 36, alignItems: "center" }}>
        {/* Score block */}
        <div>
          <div style={{ fontSize: 10.5, fontWeight: 700, letterSpacing: "0.14em", color: "var(--tt-60)", textTransform: "uppercase", marginBottom: 6 }}>
            Current
          </div>
          <div className="tnum" style={{
            fontFamily: "var(--font-primary)", fontWeight: 700,
            fontSize: 64, lineHeight: 1, letterSpacing: "-0.025em",
            color: "var(--trust-tech)"
          }}>
            {current}
          </div>
          <div style={{ display: "flex", alignItems: "center", gap: 8, marginTop: 12, flexWrap: "wrap" }}>
            <span style={{
              display: "inline-flex", alignItems: "center", gap: 6,
              padding: "4px 10px", borderRadius: 999,
              background: tier.color + "22",
              border: "1px solid " + tier.color + "44",
              color: tier.color,
              fontSize: 11, fontWeight: 700, letterSpacing: "0.04em"
            }}>
              <span style={{ width: 6, height: 6, borderRadius: "50%", background: tier.color }} />
              {tier.label.toUpperCase()}
            </span>
            <span style={{
              display: "inline-flex", alignItems: "center", gap: 4,
              fontSize: 12.5, color: "#047a62", fontWeight: 700
            }}>
              <Icon name={delta >= 0 ? "trending-up" : "trending-down"} size={13} color="#047a62" />
              {delta >= 0 ? "+" : ""}{delta} vs 12 mo
            </span>
          </div>
          <div style={{ fontSize: 11, color: "var(--tt-60)", marginTop: 10, fontVariantNumeric: "tabular-nums" }}>
            Range 300 – 850
          </div>
        </div>

        {/* Sparkline trend */}
        <div style={{ minWidth: 0 }}>
          <div style={{ display: "flex", justifyContent: "space-between", alignItems: "baseline", marginBottom: 8 }}>
            <div style={{ fontSize: 10.5, fontWeight: 700, letterSpacing: "0.12em", color: "var(--tt-60)", textTransform: "uppercase" }}>
              12-month trend
            </div>
            <div style={{ fontSize: 11, color: "var(--tt-60)", fontVariantNumeric: "tabular-nums" }}>
              {yearAgo} → {current}
            </div>
          </div>
          <div style={{
            background: "var(--tt-5)", borderRadius: 10, padding: "10px 12px 6px",
            border: "1px solid var(--border-1)"
          }}>
            <ScoreSparkline data={SCORE_HISTORY} height={70} />
            <div style={{ display: "flex", justifyContent: "space-between", fontSize: 9.5, color: "var(--tt-60)", fontWeight: 600, marginTop: 2 }}>
              <span>{SCORE_HISTORY[0].month}</span>
              <span>{SCORE_HISTORY[SCORE_HISTORY.length - 1].month}</span>
            </div>
          </div>
        </div>

        {/* Monthly reporting grid */}
        <div style={{ minWidth: 0 }}>
          <div style={{ display: "flex", justifyContent: "space-between", alignItems: "baseline", marginBottom: 8 }}>
            <div style={{ fontSize: 10.5, fontWeight: 700, letterSpacing: "0.12em", color: "var(--tt-60)", textTransform: "uppercase" }}>
              Reported by your Flex Line
            </div>
            <div style={{ fontSize: 11, color: "var(--tt-60)" }}>
              <span style={{ fontWeight: 700, color: "var(--trust-tech)" }}>{ontimeCount}</span>/12 on time
            </div>
          </div>
          <ReportingGrid data={REPORTING_HISTORY} />
          <div style={{ display: "flex", gap: 14, marginTop: 12, fontSize: 11, color: "var(--tt-60)", flexWrap: "wrap" }}>
            <span style={{ display: "inline-flex", alignItems: "center", gap: 6 }}>
              <span style={{ width: 9, height: 9, borderRadius: 2, background: "var(--funding-pool)" }} />
              On time
            </span>
            <span style={{ display: "inline-flex", alignItems: "center", gap: 6 }}>
              <span style={{ width: 9, height: 9, borderRadius: 2, background: "#e0a85f" }} />
              Late
            </span>
            <span style={{ display: "inline-flex", alignItems: "center", gap: 6 }}>
              <span style={{ width: 9, height: 9, borderRadius: 2, background: "#e07a5f" }} />
              Bounced
            </span>
          </div>
        </div>
      </div>
    </div>);
};

const FlexDashboard = ({ tweaks, selectedOffer, onDraw, onPayNow }) => {
  const { partnerName } = tweaks;
  // If the user picked an initial draw amount on the Decision page, override
  // the single draw's amount + factor so the dashboard reflects it everywhere.
  const draws = React.useMemo(() => {
    if (!selectedOffer || !selectedOffer.initialDraw) return DRAWS;
    return [{
      ...DRAWS[0],
      amount: selectedOffer.initialDraw,
      factorRate: selectedOffer.factor
    }];
  }, [selectedOffer]);
  const totalDrawnLocal = draws.reduce((sum, d) => sum + d.amount, 0);

  // Derive dashboard state from the offer the user picked on the Decision page,
  // falling back to defaults when they jumped straight to the dashboard.
  const s = React.useMemo(() => {
    if (!selectedOffer) return DASH_STATE;
    const limit = selectedOffer.limit;
    const factor = selectedOffer.factor;
    const days = selectedOffer.days || 260;
    const totalPayback = draws.reduce((sum, d) => sum + d.amount * factor, 0);
    const weeks = Math.max(1, Math.round(days / 7));
    // Round to nearest $50 like in computeTerms.
    const weeklyPayment = Math.max(50, Math.round(totalPayback / weeks / 50) * 50);
    // Roughly scale paid-so-far + payNowBalance proportionally to keep the
    // dashboard internally consistent without recomputing the whole calendar.
    const paidRatio = DASH_STATE.paidSoFar / DASH_STATE.totalPayback;
    const paidSoFar = Math.round(totalPayback * paidRatio);
    const payNowBalance = Math.max(0, totalPayback - paidSoFar);
    return {
      ...DASH_STATE,
      spendingLimit: limit,
      totalDrawn: totalDrawnLocal,
      spendingAvailability: Math.max(0, limit - totalDrawnLocal),
      factorRate: factor,
      totalPayback,
      weeklyPayment,
      paidSoFar,
      payNowBalance
    };
  }, [selectedOffer, draws, totalDrawnLocal]);
  const progressPct = Math.round(s.paidSoFar / s.totalPayback * 100);

  return (
    <div className="cap fade-up" style={{ position: "relative" }}>
      <div className="cap-shell">
        <div className="cap-header">
          <CapitalCobrand partnerName={partnerName} attribution={tweaks.revenuedAttribution} />
          <div style={{ display: "flex", alignItems: "center", gap: 8 }}>
            <button className="btn btn-text" style={{ color: "var(--tt-60)" }}>
              <Icon name="file-text" size={14} /> Agreement
            </button>
            <button className="btn btn-text" style={{ color: "var(--tt-60)" }}>
              <Icon name="settings" size={14} /> Settings
            </button>
          </div>
        </div>

        {/* HERO summary */}
        <div className="card dash-hero" style={{
          padding: 0, border: "none",
          background: "linear-gradient(135deg, var(--growth-galaxy) 0%, var(--trust-tech) 100%)",
          color: "#fff", borderRadius: 20, overflow: "hidden", position: "relative",
          marginBottom: 20
        }}>
          <div style={{ position: "absolute", right: -60, top: -60, opacity: 0.7 }}>
            <Rings size={400} palette="teal" />
          </div>
          <div className="dash-hero-grid" style={{ display: "grid", gridTemplateColumns: "1.25fr 1fr", padding: 36, position: "relative", zIndex: 1, gap: 40, alignItems: "center" }}>
            <div className="dash-hero-main">
              <Eyebrow muted style={{ color: "var(--funding-pool)" }}>Spending Availability</Eyebrow>
              <div className="dash-hero-amount tnum" style={{
                fontFamily: "var(--font-primary)", fontWeight: 700,
                fontSize: 88, lineHeight: 1, letterSpacing: "-0.035em",
                fontVariantNumeric: "tabular-nums", margin: "14px 0 18px"
              }}>
                {fmtUSD(s.spendingAvailability)}
              </div>

              {/* Utilization microbar */}
              <div className="dash-hero-bar" style={{ maxWidth: 420, marginBottom: 24 }}>
                <div style={{ height: 5, background: "rgba(255,255,255,0.10)", borderRadius: 999, overflow: "hidden" }}>
                  <div style={{
                    height: "100%",
                    width: (s.spendingLimit > 0 ? Math.min(100, s.totalDrawn / s.spendingLimit * 100) : 0) + "%",
                    background: "var(--funding-pool)",
                    borderRadius: 999,
                    transition: "width 0.3s ease-out"
                  }} />
                </div>
                <div style={{ display: "flex", justifyContent: "space-between", marginTop: 8, fontSize: 11.5, color: "rgba(255,255,255,0.62)", fontVariantNumeric: "tabular-nums" }}>
                  <span style={{ display: "inline-flex", alignItems: "center", gap: 6 }}>
                    <span style={{ width: 8, height: 8, borderRadius: 2, background: "var(--funding-pool)" }} />
                    {fmtUSD(s.totalDrawn)} drawn
                  </span>
                  <span style={{ display: "inline-flex", alignItems: "center", gap: 6 }}>
                    <span style={{ width: 8, height: 8, borderRadius: 2, background: "rgba(255,255,255,0.20)" }} />
                    {fmtUSD(s.spendingAvailability)} available
                  </span>
                </div>
              </div>

              <div className="dash-hero-blurb" style={{ fontSize: 15, color: "rgba(255,255,255,0.78)", maxWidth: 460, lineHeight: 1.5, margin: "0 0 28px" }}>
                Pull what you need, when you need it. Each draw inherits your Flex Line terms.
              </div>
              <div className="dash-hero-actions" style={{ display: "flex", gap: 10 }}>
                <Button variant="teal" size="lg" onClick={onDraw} icon="arrow-down-to-line">Take a cash draw</Button>
                <Button variant="ghost" size="lg" onClick={onPayNow} style={{ background: "rgba(255,255,255,0.10)", color: "#fff", boxShadow: "inset 0 0 0 1px rgba(255,255,255,0.20)" }}>
                  PayNow
                </Button>
              </div>
            </div>

            <div className="dash-hero-side" style={{ display: "flex", flexDirection: "column", gap: 18, alignItems: "center" }}>
              <UtilizationDonut drawn={s.totalDrawn} limit={s.spendingLimit} />

              <div className="dash-kpis" style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 10, width: "100%" }}>
                {[
                { l: "Spending Limit", v: fmtUSD(s.spendingLimit) },
                { l: "PayNow Balance", v: fmtUSD(s.payNowBalance) },
                { l: "Factor rate", v: s.factorRate.toFixed(2) },
                { l: "Weekly payment", v: "$" + s.weeklyPayment }].
                map((k, i) =>
                <div key={i} style={{
                  padding: "12px 14px",
                  background: "rgba(255,255,255,0.06)",
                  borderRadius: 10,
                  border: "1px solid rgba(255,255,255,0.08)"
                }}>
                    <div style={{ fontSize: 10, fontWeight: 700, color: "rgba(255,255,255,0.55)", textTransform: "uppercase", letterSpacing: "0.10em", marginBottom: 6 }}>
                      {k.l}
                    </div>
                    <div className="tnum" style={{ fontSize: 17, fontWeight: 700, letterSpacing: "-0.01em" }}>
                      {k.v}
                    </div>
                  </div>)}
              </div>
            </div>
          </div>
        </div>

        {/* Active draws + PayNow callout */}
        <div style={{ display: "grid", gridTemplateColumns: "1.4fr 1fr", gap: 20, marginBottom: 20 }}>
          <div className="card card-pad">
            <div style={{ display: "flex", alignItems: "flex-start", justifyContent: "space-between", marginBottom: 18 }}>
              <div>
                <Eyebrow>Active draws</Eyebrow>
                <div style={{ fontSize: 22, fontWeight: 700, marginTop: 6, letterSpacing: "-0.01em" }}>
                  {draws.length} {draws.length === 1 ? "draw" : "draws"} · {fmtUSD(s.totalDrawn)} total
                </div>
                <div style={{ fontSize: 12.5, color: "var(--tt-60)", marginTop: 4 }}>
                  Factor rate {s.factorRate.toFixed(2)} · weekly payment from your business deposits.
                </div>
              </div>
              <span className="pill pill-blue">Active</span>
            </div>

            {/* List of individual draws */}
            <div style={{ display: "flex", flexDirection: "column", gap: 8, marginBottom: 22 }}>
              {draws.map((d, i) =>
              <div key={d.id} className="dash-draw-row" style={{
                display: "grid", gridTemplateColumns: "auto 1fr auto auto",
                alignItems: "center", gap: 14,
                padding: "14px 16px",
                background: "var(--tt-5)", borderRadius: 10
              }}>
                  <div className="dash-draw-icon" style={{
                  width: 32, height: 32, borderRadius: 8,
                  background: "var(--gg-10)", color: "var(--growth-galaxy)",
                  display: "grid", placeItems: "center", flexShrink: 0
                }}>
                    <Icon name="arrow-down-left" size={14} />
                  </div>
                  <div className="dash-draw-label">
                    <div style={{ fontSize: 13.5, fontWeight: 600 }}>Draw {i + 1} · {d.label}</div>
                    <div style={{ fontSize: 11.5, color: "var(--tt-60)", marginTop: 2 }}>
                      {d.date.toLocaleDateString("en-US", { month: "long", day: "numeric", year: "numeric" })} · {d.factorRate.toFixed(2)}× factor
                    </div>
                  </div>
                  <div className="dash-draw-amount" style={{ textAlign: "right" }}>
                    <div className="tnum" style={{ fontSize: 14.5, fontWeight: 700 }}>{fmtUSD(d.amount)}</div>
                    <div className="tnum" style={{ fontSize: 11, color: "var(--tt-60)" }}>{fmtUSD(d.amount * d.factorRate)} payback</div>
                  </div>
                  <span className="dash-draw-pill pill pill-neutral" style={{ fontSize: 9.5 }}>In delivery</span>
                </div>
              )}
            </div>

            {/* Combined progress */}
            <div>
              <div style={{ display: "flex", justifyContent: "space-between", fontSize: 11, color: "var(--tt-60)", marginBottom: 8, textTransform: "uppercase", fontWeight: 700, letterSpacing: "0.10em" }}>
                <span>Combined progress</span>
                <span>{progressPct}% delivered</span>
              </div>
              <div style={{ height: 10, background: "var(--tt-5)", borderRadius: 999, overflow: "hidden", position: "relative" }}>
                <div style={{ height: "100%", width: progressPct + "%", background: "linear-gradient(90deg, var(--growth-galaxy), var(--funding-pool))", borderRadius: 999 }} />
              </div>
              <div style={{ display: "flex", justifyContent: "space-between", fontSize: 11, color: "var(--tt-60)", marginTop: 8 }}>
                <span>{fmtUSD(s.paidSoFar)} delivered</span>
                <span>{fmtUSD(s.payNowBalance)} remaining</span>
              </div>
            </div>
          </div>

          {/* PayNow callout */}
          <div className="card card-pad" style={{
            background: "linear-gradient(160deg, var(--bright-opportunity) 0%, var(--fp-20) 100%)",
            border: "none", position: "relative", overflow: "hidden"
          }}>
            <div style={{ position: "absolute", right: -40, bottom: -40, opacity: 0.4 }}>
              <Rings size={220} palette="teal" />
            </div>
            <div style={{ position: "relative", zIndex: 1 }}>
              <div style={{
                width: 36, height: 36, borderRadius: 9,
                background: "var(--trust-tech)", color: "var(--funding-pool)",
                display: "grid", placeItems: "center", marginBottom: 14
              }}>
                <Icon name="fast-forward" size={18} />
              </div>
              <Eyebrow style={{ color: "#075c3e" }}>PayNow</Eyebrow>
              <div style={{ fontSize: 22, fontWeight: 700, marginTop: 6, lineHeight: 1.2, color: "var(--trust-tech)" }}>
                Pay extra and lower your balance
              </div>
              <div style={{ fontSize: 13, color: "#0a4d36", marginTop: 8, lineHeight: 1.5 }}>
                Send any amount toward your balance. Pay it all off and we'll discount what you owe.
              </div>
              <Button variant="dark" size="md" onClick={onPayNow} style={{ marginTop: 18 }} iconAfter="arrow-right">
                Make a PayNow payment
              </Button>
            </div>
          </div>
        </div>

        {/* SBFE Business Credit Score */}
        <SBFEDashboardCard />

        {/* Payment calendar */}
        <div style={{ marginBottom: 20 }}>
          <PaymentCalendar weeklyPayment={s.weeklyPayment} />
        </div>

        {/* Transaction history */}
        <TransactionHistory
          drawAmount={draws[0].amount}
          factor={s.factorRate}
          weeklyPayment={s.weeklyPayment}
          drawDate={draws[0].date} />

        <div style={{ marginTop: 24 }}>
          <Disclosure>
            Revenued's service provides for the purchase of future receivables and is not a loan. Weekly payment amounts may be reconciled monthly based on actual receivables volume.
          </Disclosure>
        </div>
      </div>
    </div>);

};

Object.assign(window, {
  FlexDashboard, CashDrawTakeover, PayNowTakeover, DASH_STATE, DRAWS
});