/* Dulius App UI Kit — mock data (v2: Dulius programs model, Marcus / 524) */
const DULIUS = {
  user: { name: "Marcus Thompson", business: "Thompson's Kitchen", initials: "MT", plan: "Premium", industry: "Restaurant", memberSince: "January 2026" },
  score: { value: 524, band: "Fair Standing", delta: 12, updated: "Today" },
  history6mo: [479, 491, 498, 507, 512, 524],

  // Dashboard stat cards
  stats: [
    { label: "Matched funding", value: "$127,500", sub: "6 live offers available", icon: "wallet" },
    { label: "Active deals", value: "1", sub: "$20,000 Score Builder · 42% paid", icon: "briefcase" },
    { label: "Score change", value: "+12", sub: "this month", icon: "trending-up", positive: true },
  ],

  // Next-tier milestone
  milestone: { points: 76, target: "Dulius Advance", etaDays: 45 },

  // Score breakdown — 5 weighted factors (v2)
  factors: [
    { label: "Payment history", weightPct: 35, contribution: 68, impact: "High", status: "Needs improvement", tone: "warn",
      note: "Your strongest category. 2 late payments in the last 12 months are holding you back — clean payments for 60 more days and this jumps." },
    { label: "Revenue consistency", weightPct: 25, contribution: 54, impact: "High", status: "Fair", tone: "ok",
      note: "Your revenue shows some volatility. 3 of the last 6 months had deposits below your average." },
    { label: "Time in business", weightPct: 20, contribution: 82, impact: "Medium", status: "Good", tone: "good",
      note: "2 years 4 months in business. A strength — at 3 years you'll see another automatic boost." },
    { label: "Funding utilization", weightPct: 15, contribution: 60, impact: "Medium", status: "Fair", tone: "ok",
      note: "1 active deal. Paying it down consistently improves this — avoid stacking multiple deals." },
    { label: "Industry risk", weightPct: 5, contribution: 70, impact: "Low", status: "Good", tone: "good",
      note: "Restaurants carry moderate risk in our model. You can't change this, but strong performance elsewhere outweighs it." },
  ],

  // Personal credit (self-reported estimate, Dulius-verified later)
  personalCredit: { estimate: "Fair", range: "600–659", label: "Self-reported", utilization: 67, payHistory: 88, derogatory: 1, openAccounts: 6, oldest: "8 years", verified: false, fico: 612 },

  // Debt utilization — business funding only (no linked personal accounts)
  debt: {
    ratio: 42,
    obligations: [
      { name: "Score Builder", amount: "$20,000", daily: "$284", remaining: "$11,600", remainingPct: 58, payoff: "Jul 14", impact: "+18" },
      { name: "Brightline Funding", amount: "$30,000", daily: "$210", remaining: "$24,800", remainingPct: 83, payoff: "Sep 2", impact: "+12" },
    ],
    totalUtil: 67,
  },

  // Score simulator scenarios
  simulator: [
    { id: "ontime", label: "Make on-time payments for 60 days", delta: 44, score: 568 },
    { id: "util", label: "Reduce credit utilization to 40%", delta: 22, score: 546 },
    { id: "both", label: "Do both", delta: 70, score: 594, note: "You'd qualify for Dulius Advance in ~30 days" },
  ],

  // Path to next tier
  tierPath: {
    current: 524, currentTier: "Fair Standing", advanceAt: 600, eliteAt: 650,
    actions: [
      { title: "Avoid NSFs for 30 days", impact: 15, effort: "30 days", done: false },
      { title: "Make all scheduled payments on time for 60 days", impact: 25, effort: "60 days", done: false },
      { title: "Reduce personal credit utilization below 40%", impact: 22, effort: "Varies", done: false },
      { title: "Connect tax returns for bonus points", impact: 8, effort: "5 minutes", done: false },
    ],
  },

  // Dulius lending programs
  programs: [
    { id: "builder", name: "Score Builder", badge: "Start here", badgeTone: "success", amount: "$5,000 – $40,000", term: "50–100 days", factor: "1.46", orig: "6%", svc: "$49–$99/mo", eligible: true,
      desc: "Real capital fast — every payment builds your Dulius Score.", reqScore: 0 },
    { id: "advance", name: "Dulius Advance", badge: "Most popular", badgeTone: "brand", amount: "$15,000 – $75,000", term: "100–180 days", factor: "1.43", orig: "5%", svc: "$39–$89/mo", eligible: false, lockReason: "Reach a 600 Dulius Score + clean Score Builder history",
      desc: "Larger amounts, better rates — your reward for clean history.", reqScore: 600 },
    { id: "elite", name: "Dulius Elite", badge: "By qualification", badgeTone: "gold", amount: "$50,000 – $150,000", term: "9–12 months", factor: "1.40", orig: "4%", svc: "$89–$149/mo", eligible: false, lockReason: "Complete Builder + Advance, 650+ score, clean history",
      desc: "Our largest amounts and best rates, reserved for proven members.", reqScore: 650 },
  ],

  // Active deal (Deal management)
  deal: {
    program: "Score Builder", status: "Active", fundedDate: "March 14, 2026",
    original: "$20,000", factor: "1.46", payback: "$29,200", paid: "$12,264", paidPct: 42,
    remaining: "$16,936", svcFee: "$99/month", daily: "$573", paymentsMade: 21, paymentsTotal: 51,
    nextPayment: "Tomorrow", scoreImpact: 18,
    renewalNote: "You're 2% from renewal review — at your current pace, eligible in ~4 days.",
  },

  // Renewal offers — sent to you by Dulius or your other lenders on your active deals
  renewalOffers: [
    { id: "r1", lender: "Dulius Advance", initials: "DA", dulius: true, type: "Dulius program · renewal",
      renews: "Score Builder · $20,000", renewsId: "d1", amount: "$75,000", apr: "1.43 factor", term: "100–180 days",
      highlight: "Move up a tier — better factor than your current 1.46", benefit: "+$58,064 new capital", match: 100,
      expires: "7 days", status: "Renewal", tags: ["Tier upgrade", "Lower factor", "Fast renewal"] },
    { id: "r2", lender: "Brightline Funding", initials: "BF", dulius: false, type: "MCA · partner renewal",
      renews: "Brightline Funding · $30,000", renewsId: "d2", amount: "$45,000", apr: "1.40 factor", term: "150 days",
      highlight: "Your lender pre-approved a renewal at a reduced factor", benefit: "Lower rate than your current 1.42", match: 92,
      expires: "5 days", status: "Renewal", tags: ["Same-day funding", "Reduced factor"] },
  ],

  // Matched offers (Dulius programs + marketplace)
  offers: [
    { lender: "Score Builder", initials: "SB", type: "Dulius program", amount: "Up to $40,000", apr: "1.46 factor", term: "50–100 days", match: 100, tags: ["Builds your score", "Direct from Dulius"], status: "Best match", dulius: true },
    { lender: "Brightline Funding", initials: "BF", type: "MCA", amount: "$10,000 – $30,000", apr: "1.42 factor", term: "120 days", match: 87, tags: ["Same-day funding"], status: "Likely" },
    { lender: "Cedar Merchant", initials: "CM", type: "Line of credit", amount: "$5,000 – $20,000", apr: "28% APR", term: "Revolving", match: 81, tags: ["No prepay penalty"], status: "Likely" },
    { lender: "Foundry Capital", initials: "FC", type: "Term loan", amount: "$15,000 – $35,000", apr: "32% APR", term: "12 mo.", match: 74, tags: ["Build credit"], status: "Eligible" },
  ],

  // Funding history (deal-based) — multiple open loans supported
  facilities: [
    { lender: "Score Builder", type: "Dulius program", orig: "$20,000", balance: "$16,936", apr: "1.46 factor", opened: "Mar 2026", status: "Active", progress: 42, payAmt: "$573", payFreq: "Daily (Mon–Fri)", paysLeft: 30, paysTotal: 51 },
    { lender: "Brightline Funding", type: "MCA · partner", orig: "$30,000", balance: "$24,800", apr: "1.42 factor", opened: "Apr 2026", status: "Active", progress: 17, payAmt: "$495", payFreq: "Daily (Mon–Fri)", paysLeft: 50, paysTotal: 86 },
    { lender: "Score Builder", type: "Dulius program", orig: "$5,000", balance: "$0", apr: "1.46 factor", opened: "Jan 2026", status: "Paid off", progress: 100, payAmt: "$365", payFreq: "Daily (Mon–Fri)", paysLeft: 0, paysTotal: 20 },
  ],

  // Active deals a service (dispute / negotiation) can be applied to
  openDeals: [
    { id: "d1", name: "Score Builder", detail: "$20,000 · 42% paid", initials: "SB" },
    { id: "d2", name: "Brightline Funding", detail: "$30,000 · MCA · 17% paid", initials: "BF" },
  ],

  activity: [
    { icon: "check-circle-2", title: "Payment received — $573", meta: "+0.3 pts · 2 days ago", tone: "good" },
    { icon: "sparkles", title: "New offer matched — $30,000", meta: "Brightline Funding · Yesterday", tone: "info" },
    { icon: "trending-up", title: "Score updated — +12 pts", meta: "This month", tone: "good" },
    { icon: "file-check-2", title: "Document verified — Bank statements", meta: "5 days ago", tone: "neutral" },
  ],

  tips: [
    { title: "Maintain a daily balance above $3,500", body: "It boosts your revenue-consistency score." },
    { title: "You have 2 NSF events on record", body: "Avoid overdrafts for 30 days to see a score lift." },
    { title: "Confirm your credit estimate", body: "Add your approximate range to sharpen your matches." },
  ],

  // Automated Profile Analysis (Premium)
  analysis: {
    readiness: 6.4, readinessLabel: "Funding Ready — Fair",
    readinessNote: "You qualify for Score Builder right now. You're 2.1 points from Good funding readiness.",
    updated: "Today at 9:42 AM",
    bankScore: 6.1,
    bank: [
      { label: "Average monthly revenue", value: "$18,400", sub: "+8% over 3 months", status: "good" },
      { label: "Average daily balance", value: "$4,200", sub: "$800 below the Advance threshold", status: "warn" },
      { label: "Revenue consistency", value: "74%", sub: "Target 80%+", status: "warn" },
      { label: "NSF events (90 days)", value: "2", sub: "Target 0 · fixing adds +15 pts", status: "warn" },
      { label: "Existing MCA payments", value: "$284/day", sub: "Low stacking risk", status: "good" },
    ],
    bankFlow: [14.2, 16.8, 15.1, 17.9, 18.0, 18.4],
    creditScore: 6.8,
    holdingBack: [
      { title: "2 NSF events", detail: "Most impactful", fix: "Maintain a $3,000 minimum balance", timeline: "30 days", gain: 15 },
      { title: "Credit utilization 67%", detail: "High", fix: "Pay personal cards down below 40%", timeline: "Varies", gain: 22 },
      { title: "Revenue consistency 74%", detail: "Medium", fix: "Target consistent monthly deposits", timeline: "60–90 days", gain: 12 },
    ],
    qualifyNow: ["Score Builder — up to $40,000 now", "6 marketplace offers available", "Payoff letter available instantly"],
    path: [
      { when: "Today", score: 524, note: "Start your Score Builder deal" },
      { when: "30 days", score: 539, note: "0 NSF events achieved" },
      { when: "60 days", score: 568, note: "Renewal eligibility approaching" },
      { when: "90 days", score: 608, note: "Qualify for Dulius Advance" },
    ],
  },

  // Disputes & services
  services: [
    { id: "dispute", name: "Dispute Assistance", price: "$99", model: "Flat fee", icon: "shield-check",
      desc: "If issues arise between you and a lender, Dulius steps in — we review documentation, communicate directly with the lender, and work to a fair resolution.",
      includes: ["Full documentation review", "Direct communication with the lender", "Resolution recommendation", "Formal dispute filing if needed", "Status updates throughout"],
      cta: "File a dispute — $99" },
    { id: "negotiation", name: "Negotiation Service", price: "$299", model: "Only charged if funded", icon: "handshake",
      info: "You are not charged anything unless the deal funds or your terms improve.",
      desc: "Need better terms? Dulius contacts you and the lender directly to negotiate improved terms on your behalf.",
      includes: ["Full deal review", "We contact you and the lender", "Negotiate improved terms", "Written resolution agreement", "Full communication log"],
      cta: "Request negotiation — $299" },
  ],
  disputes: [
    { ref: "Score Builder · #DUL-2026-001", filed: "May 22, 2026", type: "Dispute Assistance", status: "Under review", step: 1 },
  ],

  // Funding application — what we already have vs. what we still need (★ = required)
  application: {
    onFile: [
      { group: "Business", items: [
        { label: "Legal business name", val: "Thompson's Kitchen LLC", req: true },
        { label: "EIN / Federal Tax ID", val: "82-4417741", req: true },
        { label: "Entity type", val: "LLC", req: true },
        { label: "Industry", val: "Restaurant", req: true },
        { label: "Business start date", val: "Jan 2024", req: true },
        { label: "Business address", val: "1840 Guadalupe St, Austin, TX 78701", req: true },
        { label: "Business phone", val: "(512) 555-0112", req: true },
      ] },
      { group: "Owner", items: [
        { label: "Owner full name", val: "Marcus Thompson", req: true },
        { label: "Ownership %", val: "100%", req: true },
        { label: "Date of birth", val: "04/12/1988", req: true },
        { label: "SSN", val: "412-55-8841", req: true },
        { label: "Home address", val: "920 Westlake Dr, Austin, TX 78746", req: true },
      ] },
      { group: "Financials & documents", items: [
        { label: "Avg. monthly revenue", val: "$18,400", req: true, src: "Plaid" },
        { label: "Avg. daily balance", val: "$4,200", req: true, src: "Plaid" },
        { label: "3 months bank statements", val: "Connected", req: true, src: "Plaid" },
        { label: "Government ID", val: "Verified", req: true, src: "Stripe Identity" },
        { label: "Existing positions", val: "1 · Score Builder", req: true },
      ] },
    ],
    needed: [
      { id: "useoffunds", label: "Use of funds", req: true, type: "select", options: ["Working capital", "Inventory", "Equipment", "Payroll", "Expansion", "Marketing", "Other"] },
      { id: "voidedcheck", label: "Voided check", req: true, type: "upload", note: "Required for ACH funding & repayment" },
      { id: "license", label: "Business license", req: false, type: "upload", note: "Optional — adds credibility & unlocks more offers" },
    ],
  },

  // Deal updates feed + specials/renewals + loan documents
  dealUpdates: [
    { icon: "sparkles", title: "Renewal available soon", body: "You're 2% from renewal review — eligible in ~4 days.", date: "Today", tone: "info", special: true },
    { icon: "check-circle-2", title: "Payment received — $573", body: "21 of 51 payments made · on time.", date: "2 days ago", tone: "good" },
    { icon: "trending-up", title: "Score impact +18", body: "This deal has added 18 points to your Dulius Score.", date: "This month", tone: "good" },
    { icon: "file-check-2", title: "Funding agreement signed", body: "Score Builder · $20,000 funded.", date: "Mar 14", tone: "neutral" },
  ],
  dealSpecials: [
    { icon: "arrow-up-circle", title: "Renewal → Dulius Advance", body: "Renew at 40–60% paid and move up to $75,000 at a 1.43 factor — better than your current 1.46.", cta: "Preview renewal" },
    { icon: "percent", title: "Loyalty rate cut", body: "Clean pay history unlocks a lower factor on your next deal automatically.", cta: "See terms" },
  ],
  loanDocs: [
    { name: "Funding Agreement", type: "Signed · PDF", icon: "file-text", date: "Mar 14, 2026" },
    { name: "TILA Disclosure", type: "PDF", icon: "scale", date: "Mar 14, 2026" },
    { name: "Payment Schedule", type: "PDF", icon: "calendar", date: "Mar 14, 2026" },
    { name: "ACH Authorization", type: "Signed · PDF", icon: "building-2", date: "Mar 14, 2026" },
    { name: "Payoff Letter", type: "Generate instantly — free", icon: "receipt", date: "On demand", action: true },
  ],

  // Dispute Protection (insurance-style) + lender contact
  protection: {
    name: "Dulius Dispute Protection",
    price: "$99/mo",
    proPrice: "$49/mo",
    tagline: "Like insurance for your funding.",
    desc: "If anything ever goes wrong between you and a lender, Dulius stands between you and them — documentation, direct communication, and resolution — with no per-case fee.",
    includes: ["Unlimited dispute handling (no $99 per case)", "We contact the lender on your behalf", "Documentation & resolution support", "Coverage on every active Dulius deal", "Cancel anytime"],
  },

  // Platform support
  support: {
    channels: [
      { icon: "message-square", title: "Message us", sub: "Avg. reply under 2 hours", cta: "Start a chat" },
      { icon: "phone", title: "Schedule a call", sub: "Talk to a funding advisor", cta: "Book a time" },
      { icon: "phone-call", title: "Contact a lender", sub: "We reach out on your behalf", cta: "Request outreach" },
      { icon: "mail", title: "Email", sub: "hello@dulius.com", cta: "Send email" },
    ],
    faqs: [
      { q: "How do renewals work?", a: "When you reach 40–60% paid on an active deal, you may qualify to renew — fresh capital plus an automatic review for the next tier. We notify you the moment you're eligible." },
      { q: "Does checking my score affect my credit?", a: "Never. There's no credit pull to get your Dulius Score — we score your business cash flow and your self-reported credit estimate. Your credit is only verified later, with your consent, during underwriting." },
      { q: "What does Dulius cost?", a: "The Dulius platform is free to use — checking your score and getting matched never costs a thing. For members who want more, we offer two subscriptions, Premium ($19/mo) and Pro ($49/mo), with deeper insights and tools. If you accept a funding offer, every term and cost is laid out clearly in your offer before you sign — no surprise add-on fees, no hidden charges." },
      { q: "How fast can I get funded?", a: "Score Builder applications are typically reviewed within 24–48 hours; funding arrives 1–2 business days after approval." },
    ],
  },

  // Document Center
  documents: {
    connected: [
      { name: "Chase Business Checking", via: "Plaid · live feed", status: "connected", synced: "Today" },
      { name: "Estimated credit", via: "Self-reported · verify later", status: "estimate", synced: "Fair (600–659)" },
    ],
    required: [
      { name: "3 months bank statements", status: "verified", date: "Mar 10, 2026", expires: "Sep 10, 2026", icon: "file-text" },
      { name: "Business EIN verification", status: "verified", via: "Auto-verified via Middesk", icon: "building-2" },
      { name: "Government ID", status: "verified", via: "Verified via Stripe Identity", icon: "id-card" },
      { name: "Voided check", status: "pending", date: "Uploaded yesterday", note: "Under review", icon: "receipt" },
    ],
    optional: [
      { name: "Tax returns (last 2 years)", status: "missing", boost: "+25 pts", note: "Uploading adds up to +25 points to your Dulius Score", icon: "file-spreadsheet" },
      { name: "Business license", status: "missing", note: "Adds credibility and unlocks more offers", icon: "scroll" },
      { name: "Proof of ownership", status: "missing", note: "Operating agreement or articles of incorporation", icon: "stamp" },
    ],
  },

  // Approved for funding queue
  approvals: [
    { lender: "Score Builder", initials: "SB", dulius: true, type: "Dulius program", amount: "$20,000", net: "$18,800", factor: "1.46", term: "72 days", approved: "Today", status: "Action needed",
      steps: [
        { label: "Application approved", done: true },
        { label: "Verify your bank (Plaid or bank login)", done: false },
        { label: "Upload voided check", done: false },
        { label: "Final review by Dulius", done: false },
        { label: "Funding call to confirm terms", done: false },
        { label: "Funds released to your account", done: false },
      ] },
    { lender: "Brightline Funding", initials: "BF", partner: true, type: "MCA · partner funder", amount: "$30,000", net: "$28,500", factor: "1.42", term: "120 days", approved: "Yesterday", status: "Action needed",
      steps: [
        { label: "Pre-approved by funder", done: true },
        { label: "Verify your bank (Plaid or bank login)", done: false },
        { label: "Verify business documents", done: false },
        { label: "Final review by funder", done: false },
        { label: "Funding call to confirm terms", done: false },
        { label: "Funds released to your account", done: false },
      ] },
  ],

  plans: {
    current: "Premium",
    tiers: [
      { name: "Free", monthly: 0, annual: 0, blurb: "Know where you stand.", cta: "Downgrade",
        features: ["Your Dulius Score", "Up to 2 matched offers/mo", "Funding history tracker", "Payoff letters — always free", "Document vault", "Apply for funding", "Monthly score refresh"] },
      { name: "Premium", monthly: 19, annual: 190, blurb: "See the full picture and your path to better funding.", cta: "Current plan", popular: true,
        features: ["Everything in Free", "Full score breakdown by factor", "Unlimited matched offers", "Daily score updates + alerts", "Automated profile analysis", "Personalized 30/60/90-day score path", "Debt & utilization dashboard", "Renewal & opportunity alerts"] },
      { name: "Pro", monthly: 49, annual: 490, blurb: "Every tool, priority matching, and the best service rates.", cta: "Upgrade to Pro",
        features: ["Everything in Premium", "What-if score simulator", "Full funding-readiness report", "Priority offer matching + early access", "Detailed path to each tier", "Priority support"] },
    ],
    addons: [
      { name: "Negotiation Service", byPlan: { Free: "$299", Premium: "$199", Pro: "$99" }, premiumPrice: "$199", proPrice: "$99", desc: "We negotiate your funding offer for better terms on your behalf. Only charged if you actually get funded.", note: "only if you get funded" },
      { name: "Dispute Protection", byPlan: { Free: "$99", Premium: "$69", Pro: "$39" }, premiumPrice: "$69", proPrice: "$39", desc: "Proactive coverage. If a deal gets complicated, we step in automatically — handling communication and pushing for the best possible resolution.", note: "only if resolved" },
      { name: "Dispute Assistance", byPlan: { Free: "$119", Premium: "$99", Pro: "$49" }, premiumPrice: "$99", proPrice: "$49", desc: "Reactive help when you did not have Protection and a dispute comes up. We guide and assist until it is settled.", note: "only if resolved" },
      { name: "Payoff Letter", byPlan: { Free: "Always free", Premium: "Always free", Pro: "Always free" } },
    ],
  },
};

function applyDuliusProfile(saved, source) {
  if (!saved) return false;
  const score = Number(saved.score) || DULIUS.score.value;
  const band = saved.band || DULIUS.score.band;
  const rawMatchedFunding = saved.matchedFunding || saved.matched_funding || DULIUS.stats[0].value;
  const matchedFundingNumber = typeof rawMatchedFunding === "number" ? rawMatchedFunding : Number(String(rawMatchedFunding).replace(/[^0-9.-]/g, ""));
  const matchedFunding = String(rawMatchedFunding).trim().startsWith("$")
    ? String(rawMatchedFunding)
    : Number.isFinite(matchedFundingNumber) && matchedFundingNumber > 0
      ? "$" + matchedFundingNumber.toLocaleString()
      : DULIUS.stats[0].value;
  const offers = saved.offers || saved.offers_count || 1;
  DULIUS.user = {
    ...DULIUS.user,
    name: saved.ownerName || saved.owner_name || DULIUS.user.name,
    business: saved.businessName || saved.business_name || DULIUS.user.business,
    initials: saved.initials || DULIUS.user.initials,
    plan: saved.plan || DULIUS.user.plan,
    industry: saved.industry || DULIUS.user.industry,
    memberSince: source === "supabase" ? "Synced" : "Today",
  };
  DULIUS.score = { ...DULIUS.score, value: score, band, delta: 0, updated: source === "supabase" ? "Synced" : "Just now" };
  DULIUS.history6mo = [
    Math.max(300, score - 42),
    Math.max(300, score - 34),
    Math.max(300, score - 28),
    Math.max(300, score - 18),
    Math.max(300, score - 9),
    score,
  ];
  DULIUS.stats = [
    { label: "Matched funding", value: matchedFunding, sub: offers + " live offers available", icon: "wallet" },
    { label: "Active deals", value: "0", sub: "No active funding yet", icon: "briefcase" },
    { label: "Score change", value: source === "supabase" ? "Synced" : "New", sub: source === "supabase" ? "from your saved profile" : "first Dulius Score", icon: "sparkles", positive: true },
  ];
  DULIUS.milestone = {
    ...DULIUS.milestone,
    points: score >= 600 ? Math.max(0, 650 - score) : Math.max(0, 600 - score),
    target: score >= 600 ? "Dulius Elite" : "Dulius Advance",
  };
  if (saved.factors && Array.isArray(DULIUS.factors)) {
    const byLabel = {
      "Payment history": saved.factors.paymentHistory,
      "Revenue consistency": saved.factors.revenueConsistency,
      "Time in business": saved.factors.timeInBusiness,
      "Funding utilization": saved.factors.fundingUtilization,
      "Industry risk": 70,
    };
    DULIUS.factors = DULIUS.factors.map((factor) => ({
      ...factor,
      contribution: Math.round(byLabel[factor.label] || factor.contribution),
      note: factor.label === "Funding utilization" && DULIUS.stats[1].value === "0"
        ? "No active deals yet. Your utilization starts clean — keep future funding payments on time to build score history."
        : factor.note,
    }));
  }
  DULIUS.personalCredit = {
    ...DULIUS.personalCredit,
    estimate: saved.factors && saved.factors.creditEstimate >= 80 ? "Very good" : saved.factors && saved.factors.creditEstimate >= 60 ? "Fair" : "Estimated",
    label: source === "supabase" ? "Synced from onboarding" : "Self-reported during onboarding",
    verified: false,
  };
  DULIUS.plans = { ...DULIUS.plans, current: (function(){try{var _p=JSON.parse(localStorage.getItem("dulius:plan:v1"));return (_p===null||typeof _p==="undefined")?null:_p;}catch(e){return null;}})() || saved.plan || DULIUS.plans.current };
  window.DULIUS = DULIUS;
  window.dispatchEvent(new CustomEvent("dulius:profile-updated", { detail: { source } }));
  return true;
}

(function applySavedOnboardingProfile() {
  try {
    applyDuliusProfile(JSON.parse(localStorage.getItem("dulius:onboarding:v1") || "null"), "local");
  } catch (e) {
    void("[dulius] Could not load saved onboarding profile", e && e.message);
  }
})();

async function hydrateDuliusProfileFromSupabase() {
  try {
    if (!window.Clerk) return;
    await window.Clerk.load();
    if (!window.Clerk.session) return;
    const token = await window.Clerk.session.getToken();
    if (!token) return;
    const response = await fetch("/api/auth/profile", { headers: { Authorization: "Bearer " + token } });
    if (!response.ok) return;
    const result = await response.json();
    const payload = result && result.onboarding && result.onboarding.payload;
    const profile = (payload && payload.profile) || (result && result.onboarding) || null;
    if (profile) applyDuliusProfile(profile, "supabase");
    try {
      const _ovr = await fetch("/api/member/overview", { headers: { Authorization: "Bearer " + token } });
      if (_ovr.ok) {
        const _d = await _ovr.json();
        try {
          const _p = _d.profile || {};
          const _a = (_d.applications && _d.applications[0]) || {};
          const _biz = _p.business_name || _a.business_name;
          const _own = _a.owner_name || _p.full_name;
          if (DULIUS.user) {
            if (_biz) DULIUS.user.business = _biz;
            if (_own) { DULIUS.user.name = _own; DULIUS.user.initials = _own.split(" ").map(function (w) { return w[0]; }).join("").slice(0, 2).toUpperCase(); }
          }
        } catch (_e2) {}
        DULIUS.approvals = (_d.applications || []).filter(function (a) { return a.status === "accepted" || a.status === "funded"; }).map(function (a) {
          var o = (a.payload && a.payload.offer) || {};
          var amt = a.requested_amount ? Number(a.requested_amount) : 0;
          return { lender: o.funder || "Dulius", initials: (o.funder || "DU").split(" ").map(function (w) { return w[0]; }).join("").slice(0, 2).toUpperCase(), dulius: true, type: "Funding offer", amount: amt ? ("$" + amt.toLocaleString()) : "", net: amt ? ("$" + amt.toLocaleString()) : "", factor: o.factor ? (o.factor + " factor") : "", term: "", approved: a.created_at ? new Date(a.created_at).toLocaleDateString() : "", status: a.status === "funded" ? "Funded" : "Accepted", steps: [] };
        });
        DULIUS.facilities = (_d.applications || []).filter(function (a) { return a.status === "funded"; }).map(function (a) {
          var o = (a.payload && a.payload.offer) || {};
          var amt = a.requested_amount ? Number(a.requested_amount) : 0;
          return { lender: o.funder || "Dulius", type: "Funding", orig: amt ? ("$" + amt.toLocaleString()) : "", balance: amt ? ("$" + amt.toLocaleString()) : "", apr: o.factor ? (o.factor + " factor") : "", opened: a.created_at ? new Date(a.created_at).toLocaleDateString() : "", status: "Active", progress: 0, payAmt: "", payFreq: "", paysLeft: 0, paysTotal: 0 };
        });
        const _offers = (_d.offers || []).map(function (o) {
          const amt = o.amount ? Number(o.amount) : 0;
          const st = o.status;
          return {
            lender: o.lender || "Dulius",
            initials: (o.lender || "DU").split(" ").map(function (w) { return w[0]; }).join("").slice(0, 2).toUpperCase(),
            type: "Offer from Dulius",
            amount: amt ? ("$" + amt.toLocaleString()) : "\u2014",
            apr: o.factor ? (o.factor + " factor") : "\u2014",
            term: "",
            match: 100,
            tags: [st === "accepted" ? "Accepted" : st === "declined" ? "Declined" : "Awaiting your decision"],
            status: st === "accepted" ? "Accepted" : st === "declined" ? "Declined" : "Live offer",
            dulius: true,
            live: true,
            applicationId: o.applicationId
          };
        });
        if (_offers.length) {
          DULIUS.offers = _offers;
          const _amt0 = (_d.offers[0] && _d.offers[0].amount) ? Number(_d.offers[0].amount) : 0;
          if (_amt0) { DULIUS.matchedFunding = "$" + _amt0.toLocaleString(); DULIUS.matchedFundingNumber = _amt0; }
        }
      }
    } catch (e) { void("[member offers] load failed", e); }
  } catch (e) {
    void("[dulius] Could not hydrate profile from Supabase", e && e.message);
  }
}

window.DULIUS = DULIUS;
window.applyDuliusProfile = applyDuliusProfile;
window.hydrateDuliusProfileFromSupabase = hydrateDuliusProfileFromSupabase;
window.addEventListener("load", function () { setTimeout(hydrateDuliusProfileFromSupabase, 250); });


/* member: accept/decline a broker offer */
window.duliusRespondToOffer = async function (applicationId, decision) {
  try {
    const token = window.Clerk && window.Clerk.session && await window.Clerk.session.getToken();
    if (!token) return false;
    const r = await fetch("/api/member/offers/respond", {
      method: "POST",
      headers: { "Content-Type": "application/json", Authorization: "Bearer " + token },
      body: JSON.stringify({ applicationId: applicationId, decision: decision })
    });
    if (!r.ok) return false;
    ((window.DULIUS && window.DULIUS.offers) || []).forEach(function (o) {
      if (o.applicationId === applicationId) {
        o.status = decision === "accepted" ? "Accepted" : "Declined";
        o.live = false;
        o.tags = [decision === "accepted" ? "Accepted \u2014 we'll be in touch" : "Declined"];
      }
    });
    window.dispatchEvent(new CustomEvent("dulius:profile-updated"));
    return true;
  } catch (e) { console.warn("[respond] failed", e); return false; }
};


/* member: documents (Supabase Storage) */
window.duliusUploadDocument = async function (file, doc) {
  try {
    var token = window.Clerk && window.Clerk.session && await window.Clerk.session.getToken();
    if (!token || !file) return false;
    var dataUrl = await new Promise(function (res, rej) { var r = new FileReader(); r.onload = function () { res(r.result); }; r.onerror = rej; r.readAsDataURL(file); });
    var slot = (doc && (doc.name || doc.label)) || "";
    var key = slot ? slot.replace(/[^A-Za-z0-9]+/g, "-").slice(0, 40) : "";
    var fname = (key ? key + "__" : "") + (file.name || "upload");
    var resp = await fetch("/api/member/documents", { method: "POST", headers: { "Content-Type": "application/json", Authorization: "Bearer " + token }, body: JSON.stringify({ filename: fname, contentType: file.type || "application/octet-stream", dataBase64: dataUrl }) });
    if (!resp.ok) return false;
    await window.duliusLoadDocuments();
    return true;
  } catch (e) { console.warn("[docs upload]", e); return false; }
};
window.duliusLoadDocuments = async function () {
  try {
    var token = window.Clerk && window.Clerk.session && await window.Clerk.session.getToken();
    if (!token) return;
    var resp = await fetch("/api/member/documents", { headers: { Authorization: "Bearer " + token } });
    if (!resp.ok) return;
    var d = await resp.json();
    var files = d.documents || [];
    if (!window.DULIUS || !window.DULIUS.documents) return;
    function matchSlot(slot) {
      var key = String(slot.name || "").replace(/[^A-Za-z0-9]+/g, "-").slice(0, 40);
      var hit = files.find(function (f) { return f.name.indexOf(key + "__") === 0; });
      if (hit) { slot.status = "uploaded"; slot.uploaded = true; slot.url = hit.url; slot.date = hit.uploadedAt ? new Date(hit.uploadedAt).toLocaleDateString() : ""; slot.fileName = hit.name.replace(/^[^_]*__/, ""); }
      else { slot.status = "missing"; slot.uploaded = false; slot.url = null; slot.date = ""; }
      return slot;
    }
    (window.DULIUS.documents.required || []).forEach(matchSlot);
    (window.DULIUS.documents.optional || []).forEach(matchSlot);
    window.dispatchEvent(new CustomEvent("dulius:profile-updated"));
  } catch (e) { console.warn("[docs load]", e); }
};
if (typeof window !== "undefined") {
  var _docsOnce = function () { window.removeEventListener("dulius:profile-updated", _docsOnce); if (window.duliusLoadDocuments) window.duliusLoadDocuments(); };
  window.addEventListener("dulius:profile-updated", _docsOnce);
}


/* ---- Profile + Support: real server persistence (Cowork) ---- */
async function _duliusAuthToken() {
  try { await window.Clerk.load(); return (window.Clerk.session && await window.Clerk.session.getToken()) || null; } catch (e) { return null; }
}
window.duliusSaveProfile = async function (profile) {
  try {
    const token = await _duliusAuthToken(); if (!token) return false;
    const r = await fetch("/api/member/profile", { method: "POST", headers: { "Content-Type": "application/json", Authorization: "Bearer " + token }, body: JSON.stringify({ profile: profile || {} }) });
    return r.ok;
  } catch (e) { return false; }
};
window.duliusLoadProfile = async function () {
  try {
    const token = await _duliusAuthToken(); if (!token) return;
    const r = await fetch("/api/member/profile", { headers: { Authorization: "Bearer " + token } });
    if (!r.ok) return;
    const d = await r.json();
    const a = d.application || {}, acc = d.account || {}, pl = (a && a.payload) || {};
    const saved = d.profile;
    const pick = function () { for (var i = 0; i < arguments.length; i++) { var v = pl[arguments[i]]; if (v != null && v !== "") return v; } return ""; };
    var merged;
    if (saved && Object.keys(saved).length) {
      merged = saved;
    } else {
      merged = {
        ownerName: a.owner_name || acc.full_name || pick("ownerName","owner_name","fullName","contactName","ownerFullName") || "",
        businessName: a.business_name || acc.business_name || pick("businessName","business_name","company","companyName") || "",
        legalName: pick("legalName","legal_name","legalBusinessName") || a.business_name || "",
        email: a.email || acc.email || pick("email") || "",
        phone: pick("phone","phoneNumber","phone_number","mobile") || "",
        entity: pick("entity","entityType","businessType","entity_type","structure") || "",
        industry: pick("industry","industryType","sector") || "",
        founded: pick("founded","yearFounded","startDate","timeInBusiness","foundedYear","established") || "",
        revenue: pick("revenue","annualRevenue","monthlyRevenue","annual_revenue","monthly_revenue") || "",
        employees: pick("employees","employeeCount","numEmployees","headcount") || "",
        ein: pick("ein","EIN","taxId","tax_id","federalTaxId") || "",
        website: pick("website","url","site","webAddress") || "",
        address: pick("address","street","address1","streetAddress","addressLine1") || "",
        city: pick("city") || "",
        state: pick("state","region","province") || "",
        zip: pick("zip","zipCode","postalCode","zip_code","postal_code") || ""
      };
    }
    var KEY = "dulius:business-profile:v1";
    var existing = null; try { existing = localStorage.getItem(KEY); } catch (e) {}
    var hasSaved = saved && Object.keys(saved).length;
    if (hasSaved || !existing) {
      try { localStorage.setItem(KEY, JSON.stringify(merged)); } catch (e) {}
      try { window.dispatchEvent(new CustomEvent("dulius:profile-updated")); } catch (e) {}
    }
  } catch (e) {}
};
window.duliusSubmitSupport = async function (ticket) {
  try {
    const token = await _duliusAuthToken(); if (!token) return false;
    const t = ticket || {};
    const r = await fetch("/api/member/support", { method: "POST", headers: { "Content-Type": "application/json", Authorization: "Bearer " + token }, body: JSON.stringify({ subject: t.topic || t.subject || "", message: t.message || t.detail || t.body || "", category: t.topic || t.category || null, channel: "form" }) });
    return r.ok;
  } catch (e) { return false; }
};
(function () {
  var done = false;
  window.addEventListener("dulius:profile-updated", function once() {
    if (done) return; done = true;
    window.removeEventListener("dulius:profile-updated", once);
    try { window.duliusLoadProfile(); } catch (e) {}
  });
})();


/* ---- Disputes / concierge requests (Cowork) ---- */
window.duliusSubmitRequest = async function (payload) {
  try {
    const token = await _duliusAuthToken(); if (!token) return false;
    const r = await fetch("/api/member/requests", { method: "POST", headers: { "Content-Type": "application/json", Authorization: "Bearer " + token }, body: JSON.stringify(payload || {}) });
    return r.ok;
  } catch (e) { return false; }
};
function _duliusComputeOpenDeals() {
  try {
    var offers = (window.DULIUS && window.DULIUS.offers) || [];
    var deals = offers.filter(function (o) { return o && o.applicationId && (o.live || /accept|fund|active|progress|approved/i.test(o.status || "")); }).map(function (o) {
      return { id: o.applicationId, name: o.businessName || o.lender || "Your deal", detail: [o.amount, o.status].filter(Boolean).join(" \u00b7 "), initials: o.initials || "DU", services: [], disputes: [] };
    });
    if (window.DULIUS) window.DULIUS.openDeals = deals;
  } catch (e) {}
}
window.addEventListener("dulius:profile-updated", _duliusComputeOpenDeals);


/* keep openDeals in sync as offers hydrate in (self-healing, ~18s window) */
(function _duliusOpenDealsScheduler() {
  var n = 0;
  var iv = setInterval(function () {
    try { _duliusComputeOpenDeals(); } catch (e) {}
    if (++n >= 12) clearInterval(iv);
  }, 1500);
})();


/* auto-hydrate the member's real data on boot, once Clerk session is ready */
(function _duliusBootHydrate() {
  var tries = 0, started = false;
  function go() {
    if (started) return;
    try {
      if (window.Clerk && window.Clerk.session) {
        started = true;
        Promise.resolve(window.hydrateDuliusProfileFromSupabase && window.hydrateDuliusProfileFromSupabase()).catch(function () {});
        return;
      }
    } catch (e) {}
    if (++tries < 60) setTimeout(go, 500);
  }
  try { if (window.Clerk && window.Clerk.load) { window.Clerk.load().then(go).catch(go); } } catch (e) {}
  go();
})();


/* ---- Plan + settings persistence (Cowork) ---- */
window.duliusSaveSettings = async function (settings) {
  try {
    const token = await _duliusAuthToken(); if (!token) return false;
    const r = await fetch("/api/member/settings", { method: "POST", headers: { "Content-Type": "application/json", Authorization: "Bearer " + token }, body: JSON.stringify({ settings: settings || {} }) });
    return r.ok;
  } catch (e) { return false; }
};
window.duliusSavePlan = async function (plan) {
  try { return await window.duliusSaveSettings({ plan: plan }); } catch (e) { return false; }
};
window.duliusLoadSettings = async function () {
  try {
    const token = await _duliusAuthToken(); if (!token) return;
    const r = await fetch("/api/member/settings", { headers: { Authorization: "Bearer " + token } });
    if (!r.ok) return;
    const d = await r.json();
    const s = d.settings;
    if (window.DULIUS && s) window.DULIUS.settings = s;
    if (s && typeof s.plan !== "undefined" && s.plan !== null) {
      try { localStorage.setItem("dulius:plan:v1", JSON.stringify(s.plan)); } catch (e) {}
      try { if (window.DULIUS && window.DULIUS.plans) window.DULIUS.plans.current = s.plan; } catch (e) {}
      try { window.dispatchEvent(new CustomEvent("dulius:profile-updated")); } catch (e) {}
      try { window.dispatchEvent(new CustomEvent("dulius:plan-updated")); } catch (e) {}
    }
  } catch (e) {}
};
(function () {
  var done = false;
  window.addEventListener("dulius:profile-updated", function once() {
    if (done) return; done = true;
    window.removeEventListener("dulius:profile-updated", once);
    try { window.duliusLoadSettings(); } catch (e) {}
  });
})();


/* ---- Dulius Score: fetch computed score + populate the score screens ---- */
window.duliusLoadScore = async function () {
  try {
    const token = await _duliusAuthToken(); if (!token) return;
    const r = await fetch("/api/member/score", { headers: { Authorization: "Bearer " + token } });
    if (!r.ok) return;
    const d = await r.json();
    if (!window.DULIUS) return;
    if (d.score) window.DULIUS.score = d.score;
    if (d.factors) window.DULIUS.factors = d.factors;
    if (d.personalCredit) window.DULIUS.personalCredit = d.personalCredit;
    if (d.debt) window.DULIUS.debt = d.debt;
    if (d.simulator) window.DULIUS.simulator = d.simulator;
    if (d.analysis) window.DULIUS.analysis = d.analysis;
    try { window.dispatchEvent(new CustomEvent("dulius:profile-updated")); } catch (e) {}
  } catch (e) {}
};
(function () {
  var done = false;
  window.addEventListener("dulius:profile-updated", function once() {
    if (done) return; done = true;
    window.removeEventListener("dulius:profile-updated", once);
    try { window.duliusLoadScore(); } catch (e) {}
  });
})();


/* ensure the score loads once Clerk session is ready (avoids pre-auth race) */
(function _duliusScoreScheduler() {
  var n = 0;
  var iv = setInterval(function () {
    n++;
    try {
      if (window.Clerk && window.Clerk.session && window.duliusLoadScore) {
        window.duliusLoadScore();
        if (n >= 2) clearInterval(iv);
      }
    } catch (e) {}
    if (n >= 20) clearInterval(iv);
  }, 1500);
})();


/* ---- save self-reported score inputs + recompute ---- */
window.duliusSaveScoreInputs = async function (inputs) {
  try {
    const token = await _duliusAuthToken(); if (!token) return false;
    var existing = {};
    try { const r = await fetch("/api/member/settings", { headers: { Authorization: "Bearer " + token } }); if (r.ok) { const d = await r.json(); existing = (d && d.settings) || {}; } } catch (e) {}
    const merged = Object.assign({}, existing, { scoreInputs: Object.assign({}, existing.scoreInputs || {}, inputs || {}) });
    const r2 = await fetch("/api/member/settings", { method: "POST", headers: { "Content-Type": "application/json", Authorization: "Bearer " + token }, body: JSON.stringify({ settings: merged }) });
    if (r2.ok) { if (window.DULIUS) window.DULIUS.settings = merged; if (window.duliusLoadScore) await window.duliusLoadScore(); }
    return r2.ok;
  } catch (e) { return false; }
};


/* ---- Sync funding checklist + booked funding call from the deal (admin-managed) ---- */
window.duliusLoadServicing = async function () {
  try {
    const token = await _duliusAuthToken(); if (!token) return;
    const r = await fetch("/api/member/overview", { headers: { Authorization: "Bearer " + token } });
    if (!r.ok) return;
    const d = await r.json();
    const apps = d.applications || [];
    if (!window.DULIUS || !Array.isArray(window.DULIUS.approvals)) return;
    var changed = false;
    window.DULIUS.approvals.forEach(function (ap) {
      var app = apps.find(function (a) { var o = (a.payload && a.payload.offer) || {}; return o.funder && ap.lender && String(o.funder).toLowerCase() === String(ap.lender).toLowerCase(); })
        || apps.find(function (a) { return /accept|fund/i.test(a.status || ""); });
      var serv = (app && app.payload && app.payload.servicing) || {};
      var defSteps = [
        { label: "Application approved", done: true },
        { label: "Bank verified", done: false },
        { label: "Voided check received", done: false },
        { label: "Final review", done: false },
        { label: "Funding call", done: false },
        { label: "Funds released", done: false }
      ];
      var steps = (Array.isArray(serv.steps) && serv.steps.length) ? serv.steps.map(function (s) { return { label: s.label, done: !!s.done }; }) : defSteps;
      if (serv.fundingCall && serv.fundingCall.when) {
        steps = steps.map(function (s) { return /funding call/i.test(s.label) ? { label: "Funding call \u00b7 " + serv.fundingCall.when, done: s.done } : s; });
        ap.fundingCall = serv.fundingCall;
      }
      if (JSON.stringify(ap.steps) !== JSON.stringify(steps)) { ap.steps = steps; changed = true; }
    });
    if (changed) { try { window.dispatchEvent(new CustomEvent("dulius:profile-updated")); } catch (e) {} }
  } catch (e) {}
};
(function () {
  var n = 0;
  var iv = setInterval(function () {
    n++;
    try { if (window.DULIUS && Array.isArray(window.DULIUS.approvals) && window.Clerk && window.Clerk.session && window.duliusLoadServicing) window.duliusLoadServicing(); } catch (e) {}
    if (n >= 15) clearInterval(iv);
  }, 4000);
})();

// build 1780608606372
