/* ===== MaxFi mock data + finance helpers ===== */

const fmtFull = (n) => '₹' + Math.round(n).toLocaleString('en-IN');
// Indian short form: L (lakh) / Cr (crore)
function fmtINR(n, dp = 2) {
  const a = Math.abs(n);
  let s;
  if (a >= 1e7) s = (n / 1e7).toFixed(dp) + ' Cr';
  else if (a >= 1e5) s = (n / 1e5).toFixed(dp) + ' L';
  else if (a >= 1e3) s = (n / 1e3).toFixed(a >= 1e4 ? 0 : 1) + 'k';
  else s = Math.round(n).toString();
  return '₹' + s;
}

const USER = { name: 'Arjun', initials: 'AM', age: 31 };

const NETWORTH = {
  total: 8842000,
  deltaMonth: 184200,
  deltaPct: 2.13,
  cash: 942000,
  invest: 6480000,
  retirement: 1420000,
  // 12-month trail for sparkline (oldest -> newest)
  trail: [6.9, 7.05, 6.82, 7.3, 7.6, 7.45, 7.9, 8.1, 8.0, 8.35, 8.66, 8.84],
};

const SPEND = {
  month: 'May',
  spent: 142380,
  budget: 165000,
  cats: [
    { name: 'Food & Dining', val: 38600, color: '#e58163' },
    { name: 'Shopping',      val: 34200, color: '#d4af5c' },
    { name: 'Bills & Utils', val: 27800, color: '#7fa8d9' },
    { name: 'Groceries',     val: 21300, color: '#5cc89a' },
    { name: 'Transport',     val: 12480, color: '#b48ad9' },
    { name: 'Other',         val: 8000,  color: '#6b675f' },
  ],
};

// transactions parsed from SMS
const TXNS = [
  { id:1, merchant:'Amazon', cat:'Shopping', amt:4299, time:'Today · 2:14 PM', card:'millennia', last4:'4821',
    sms:'Spent Rs.4299.00 On HDFC Bank Card xx4821 At AMAZON on 31-05-26. Avl Lmt Rs.1,24,500',
    missed:{ better:'amazonpay', extra:172 } },
  { id:2, merchant:'Swiggy', cat:'Food & Dining', amt:684, time:'Today · 1:02 PM', card:'ace', last4:'9032',
    sms:'INR 684.00 spent on Axis Bank Card xx9032 at SWIGGY on 31-May. Avbl Lmt INR 2,18,000' },
  { id:3, merchant:'Blue Tokai Coffee', cat:'Food & Dining', amt:520, time:'Today · 9:48 AM', card:'ace', last4:'9032',
    sms:'INR 520.00 spent on Axis Bank Card xx9032 at BLUE TOKAI on 31-May.' },
  { id:4, merchant:'BESCOM Electricity', cat:'Bills & Utils', amt:3120, time:'Yesterday · 7:20 PM', card:'ace', last4:'9032',
    sms:'Rs 3120 paid via GPay to BESCOM from Axis xx9032 on 30-05-26.' },
  { id:5, merchant:'BigBasket', cat:'Groceries', amt:2840, time:'Yesterday · 11:15 AM', card:'amazonpay', last4:'7745',
    sms:'Transaction of Rs 2840.00 done on ICICI Card xx7745 at BIGBASKET on 30-May-26.' },
  { id:6, merchant:'Uber', cat:'Transport', amt:318, time:'Yesterday · 9:02 AM', card:'ace', last4:'9032',
    sms:'INR 318.00 spent on Axis Bank Card xx9032 at UBER on 30-May.' },
  { id:7, merchant:'Myntra', cat:'Shopping', amt:2199, time:'Thu · 8:30 PM', card:'millennia', last4:'4821',
    sms:'Spent Rs.2199.00 On HDFC Bank Card xx4821 At MYNTRA on 29-05-26.' },
  { id:8, merchant:'Indian Oil', cat:'Transport', amt:2000, time:'Thu · 6:10 PM', card:'idfc', last4:'6610',
    sms:'Rs.2000.00 spent on IDFC FIRST Card xx6610 at INDIAN OIL on 29-05-26. Fuel surcharge waived.' },
];

// ---- cards & reward rules ----
const CARDS = [
  { id:'millennia', name:'HDFC Millennia', issuer:'HDFC', net:'Mastercard', last4:'4821',
    fee:1000, waiver:100000, spent:78400, hue:'#c9952f',
    tagline:'5% on Amazon, Flipkart, Swiggy', },
  { id:'amazonpay', name:'Amazon Pay ICICI', issuer:'ICICI', net:'Visa', last4:'7745',
    fee:0, waiver:0, spent:51200, hue:'#2b6cb0',
    tagline:'5% on Amazon · lifetime free', },
  { id:'ace', name:'Axis ACE', issuer:'Axis', net:'Visa', last4:'9032',
    fee:499, waiver:200000, spent:142000, hue:'#8a3ffb',
    tagline:'5% bills · 4% food · 1.5% flat', },
  { id:'idfc', name:'IDFC FIRST Millennia', issuer:'IDFC', net:'Rupay', last4:'6610',
    fee:0, waiver:0, spent:24600, hue:'#7a1f2b',
    tagline:'10X on incremental spend', },
  { id:'sbi', name:'SBI SimplyCLICK', issuer:'SBI', net:'Visa', last4:'3308',
    fee:499, waiver:100000, spent:38900, hue:'#1f6f8b',
    tagline:'10X with online partners', },
];

// reward % by card x category  (effective realised value %)
const REWARDS = {
  millennia: { Amazon:5.0, Flipkart:5.0, 'Food delivery':5.0, Travel:1.0, Fuel:0, Bills:1.0, Groceries:1.0, Offline:1.0, 'Online (other)':1.0, _cap:'₹1,000 cashback / month' },
  amazonpay: { Amazon:5.0, Flipkart:1.0, 'Food delivery':1.0, Travel:1.0, Fuel:0, Bills:2.0, Groceries:1.0, Offline:1.0, 'Online (other)':1.0, _cap:'No cap · no expiry' },
  ace:       { Amazon:1.5, Flipkart:1.5, 'Food delivery':4.0, Travel:1.5, Fuel:0, Bills:5.0, Groceries:1.5, Offline:1.5, 'Online (other)':1.5, _cap:'5%/4% capped ₹500 each' },
  idfc:      { Amazon:1.67, Flipkart:1.67, 'Food delivery':1.67, Travel:1.67, Fuel:0, Bills:0.75, Groceries:1.0, Offline:1.0, 'Online (other)':1.67, _cap:'10X only above ₹20k/mo' },
  sbi:       { Amazon:1.25, Flipkart:2.5, 'Food delivery':1.25, Travel:2.5, Fuel:0, Bills:0.25, Groceries:0.25, Offline:0.25, 'Online (other)':1.25, _cap:'10X with select partners' },
};
const CATEGORIES = ['Amazon','Flipkart','Food delivery','Bills','Travel','Groceries','Fuel','Offline','Online (other)'];
const CAT_NOTE = {
  Fuel: 'Most cards exclude fuel from rewards — only surcharge waiver applies.',
  Bills: 'Rent, wallet loads & govt payments are usually excluded.',
  Travel: 'Best value via co-brand travel cards & portal redemptions.',
};

function rankCards(category, amount) {
  return CARDS.map(c => {
    const pct = REWARDS[c.id][category] ?? 1;
    return { card:c, pct, value: amount * pct / 100, cap: REWARDS[c.id]._cap };
  }).sort((a,b) => b.value - a.value);
}

// ---- card usage: fee-waiver / spend milestones / reward caps ----
const CARD_STATUS = {
  sbi: {
    spentMonth:12600, rewardsMonth:310,
    milestones:[ { label:'Fee waiver', cur:95400, tgt:100000, reward:'₹499 fee waived + ₹2,000 voucher', period:'this year' } ],
    cap:null,
  },
  idfc: {
    spentMonth:14200, rewardsMonth:180,
    milestones:[ { label:'10X rewards tier', cur:14200, tgt:20000, reward:'10X on every spend past ₹20k', period:'this month' } ],
    cap:null,
  },
  millennia: {
    spentMonth:34200, rewardsMonth:1000,
    milestones:[
      { label:'Fee waiver', cur:78400, tgt:100000, reward:'₹1,000 fee waived', period:'this year' },
      { label:'Quarterly voucher', cur:62000, tgt:100000, reward:'₹1,000 Myntra voucher', period:'this quarter' },
    ],
    cap:{ label:'Monthly cashback cap', used:1000, cap:1000, note:'Maxed out — move online spends to Amazon Pay ICICI until 1 Jun' },
  },
  ace: {
    spentMonth:41800, rewardsMonth:1240,
    milestones:[ { label:'Fee waiver', cur:142000, tgt:200000, reward:'₹499 fee waived', period:'this year' } ],
    cap:{ label:'Bonus 5% / 4% cap', used:430, cap:500, note:'₹70 of accelerated cashback left this month' },
  },
  amazonpay: {
    spentMonth:28400, rewardsMonth:920, free:true,
    milestones:[], cap:null,
    note:'Lifetime free · no caps · no milestones. Spend freely — best for Amazon, bills & everyday use.',
  },
};

function cardMilestoneGap(c) {
  const s = CARD_STATUS[c.id]; if (!s) return Infinity;
  const open = (s.milestones||[]).filter(m=>m.cur<m.tgt).map(m=>m.tgt-m.cur);
  return open.length ? Math.min(...open) : (s.free ? 1e9 : 1e8);
}
function cardsByUrgency() {
  return [...CARDS].sort((a,b)=>cardMilestoneGap(a)-cardMilestoneGap(b));
}
function cardNudges() {
  const out = [];
  CARDS.forEach(c=>{
    const s = CARD_STATUS[c.id]; if (!s) return;
    (s.milestones||[]).forEach(m=>{ if (m.cur<m.tgt) out.push({ card:c, m, remaining:m.tgt-m.cur }); });
  });
  return out.sort((a,b)=>a.remaining-b.remaining);
}
function cardStatusOf(c) {
  const s = CARD_STATUS[c.id];
  if (!s) return { label:'—', tone:'dim' };
  if (s.cap && s.cap.used >= s.cap.cap) return { label:'Cap maxed', tone:'red' };
  const waiver = (s.milestones||[]).find(m=>/waiver/i.test(m.label));
  if (waiver && waiver.cur >= waiver.tgt) return { label:'Fee waived', tone:'green' };
  const gap = cardMilestoneGap(c);
  if (gap <= 8000) return { label:'So close', tone:'gold' };
  if (s.free) return { label:'Free & open', tone:'blue' };
  return { label:'In progress', tone:'dim' };
}

const cardById = (id) => CARDS.find(c => c.id === id);

// ---- recommended new cards (offers based on spend patterns) ----
const NEW_CARDS = [
  { id:'swiggyhdfc', name:'Swiggy HDFC Bank', issuer:'HDFC', net:'Mastercard', hue:'#e8533f',
    reason:'You spend ₹38.6k/mo on food & dining', perk:'10% cashback on Swiggy · 5% on online spends',
    extraYr:14200, fee:'₹500 · waived at ₹2L', tags:['10% Swiggy','5% online'] },
  { id:'tataneu', name:'Tata Neu Infinity', issuer:'HDFC', net:'Rupay', hue:'#6d3bf5',
    reason:'High grocery & BigBasket spends', perk:'5% NeuCoins on Tata brands · UPI rewards',
    extraYr:9800, fee:'₹1,499 · waived at ₹3L', tags:['5% Tata','UPI rewards'] },
];

// ---- mutual fund holdings (Kuvera-style portfolio) ----
const EQUITY_CATS = ['Flexi Cap','Large Cap','Mid Cap','Small Cap','ELSS'];
function assetClass(cat) {
  if (cat === 'Debt') return 'Debt';
  if (cat === 'Gold ETF') return 'Gold';
  return 'Equity';
}
const FUNDS = [
  { id:'ppfcc',  name:'Parag Parikh Flexi Cap', cat:'Flexi Cap', plan:'Direct',  invested:1050000, current:1432000, ret3y:24.1, catRet3y:19.8, erReg:1.42, erDir:0.63, heldMo:38 },
  { id:'mirae',  name:'Mirae Asset Large Cap',  cat:'Large Cap', plan:'Regular', invested:880000,  current:980000,  ret3y:14.2, catRet3y:16.1, erReg:1.55, erDir:0.54, heldMo:31 },
  { id:'axisbc', name:'Axis Bluechip',          cat:'Large Cap', plan:'Regular', invested:780000,  current:812000,  ret3y:11.3, catRet3y:16.1, erReg:1.58, erDir:0.59, heldMo:44 },
  { id:'hdfcmid',name:'HDFC Mid-Cap Opportunities', cat:'Mid Cap', plan:'Direct', invested:640000, current:905000, ret3y:28.6, catRet3y:24.2, erReg:1.49, erDir:0.74, heldMo:33 },
  { id:'sbism',  name:'SBI Small Cap',          cat:'Small Cap', plan:'Direct',  invested:610000,  current:524000,  ret3y:21.0, catRet3y:26.4, erReg:1.61, erDir:0.66, heldMo:14 },
  { id:'quant',  name:'Quant ELSS Tax Saver',   cat:'ELSS',      plan:'Regular', invested:480000,  current:686000,  ret3y:27.2, catRet3y:20.1, erReg:1.75, erDir:0.77, heldMo:40 },
  { id:'icicid', name:'ICICI Pru Corporate Bond', cat:'Debt',    plan:'Direct',  invested:720000,  current:780000,  ret3y:7.4,  catRet3y:7.1,  erReg:0.59, erDir:0.34, heldMo:27 },
  { id:'gold',   name:'Nippon India Gold BeES', cat:'Gold ETF',  plan:'Direct',  invested:300000,  current:361000,  ret3y:15.2, catRet3y:15.0, erReg:0.0,  erDir:0.0,  heldMo:22 },
];
const TARGET_ALLOC = { Equity:70, Debt:22, Gold:8 };

function portfolioStats() {
  const invested = FUNDS.reduce((s,f)=>s+f.invested,0);
  const current  = FUNDS.reduce((s,f)=>s+f.current,0);
  const gain = current - invested;
  const alloc = { Equity:0, Debt:0, Gold:0 };
  FUNDS.forEach(f => alloc[assetClass(f.cat)] += f.current);
  const allocPct = Object.fromEntries(Object.entries(alloc).map(([k,v])=>[k, v/current*100]));
  const regular = FUNDS.filter(f=>f.plan==='Regular');
  const regularValue = regular.reduce((s,f)=>s+f.current,0);
  const annualLeak = regular.reduce((s,f)=>s + f.current*(f.erReg-f.erDir)/100, 0);
  const leak20 = annualLeak * ((Math.pow(1.11,20)-1)/0.11);
  const laggards = FUNDS.filter(f=>assetClass(f.cat)==='Equity' && f.ret3y < f.catRet3y - 1.5);
  const losers = FUNDS.filter(f=>f.current < f.invested);
  const lossAvail = losers.reduce((s,f)=>s + (f.invested-f.current), 0);
  const taxSaved = lossAvail * 0.125;
  const drift = Object.fromEntries(Object.keys(TARGET_ALLOC).map(k=>[k, allocPct[k]-TARGET_ALLOC[k]]));
  const equityExcess = Math.max(0, drift.Equity)/100 * current;
  return { invested, current, gain, gainPct:gain/invested*100, alloc:allocPct, allocAbs:alloc,
    regular, regularValue, annualLeak, leak20, laggards, losers, lossAvail, taxSaved, drift, equityExcess };
}
// deterministic projection + lightweight monte-carlo success estimate
function fireProject({ corpus, monthly, returnPct, inflationPct, swrPct, annualExpense, targetCorpus }) {
  const realReturn = (1 + returnPct/100) / (1 + inflationPct/100) - 1; // real growth
  const fiNumber = annualExpense / (swrPct/100);                       // full FI corpus (today's money)
  const target = (targetCorpus != null) ? targetCorpus : fiNumber;     // what we actually project toward
  let bal = corpus, yrs = 0;
  const series = [{ y:0, v:corpus }];
  while (bal < target && yrs < 60) {
    bal = bal * (1 + realReturn) + monthly * 12;
    yrs++;
    series.push({ y:yrs, v:bal });
  }
  const reached = bal >= target;
  // crude monte-carlo: vol ~ equity heavy; success = f(buffer, swr)
  const buffer = (bal >= target) ? Math.min(1, (corpus + monthly*12*yrs) / target) : 0;
  let success = Math.max(8, Math.min(96, Math.round(
    96 - (swrPct - 2.6) * 26 - Math.max(0, returnPct - 11) * -2 - (yrs > 20 ? (yrs-20)*0.6 : 0)
  )));
  if (!reached) success = 0;
  const coast = corpus * Math.pow(1 + realReturn, Math.max(0, 60 - (31 + yrs))) >= fiNumber;
  return { realReturn, fiNumber, target, years: yrs, reached, success, series, coast };
}

// ---- FIRE flavours: target derived from SMS-tracked spend, then editable ----
const TRACKED_MONTHLY = 95000;                 // smoothed essential spend from tracking
const TRACKED_ANNUAL  = TRACKED_MONTHLY * 12;  // ₹11.4 L / yr
const FIRE_TYPES = [
  { id:'lean',    label:'Lean',    mult:0.65, blurb:'Frugal — essentials covered, minimal lifestyle' },
  { id:'regular', label:'Regular', mult:1.0,  blurb:'Maintain your current lifestyle in retirement' },
  { id:'fat',     label:'Fat',     mult:1.65, blurb:'Comfortable — travel, dining, zero compromises' },
  { id:'coast',   label:'Coast',   mult:1.0,  coast:true, blurb:'Invest to a point, then let it compound to FI by 60' },
  { id:'barista', label:'Barista', mult:1.0,  baristaIncome:360000, blurb:'Part-time income (₹3L/yr) covers part of expenses' },
];
const fireTypeById = (id) => FIRE_TYPES.find(t=>t.id===id) || FIRE_TYPES[1];

// given the chosen type + (editable) annual expense, compute the corpus target
function fireTypeTarget(typeId, annualExpense, swrPct, realReturn, age) {
  const t = fireTypeById(typeId);
  let covered = annualExpense;
  if (t.baristaIncome) covered = Math.max(0, annualExpense - t.baristaIncome);
  const fiNumber = covered / (swrPct/100);          // corpus to fully fund covered expenses
  let target = fiNumber, coastNumber = null;
  if (t.coast) { coastNumber = fiNumber / Math.pow(1 + realReturn, Math.max(1, 60 - age)); target = coastNumber; }
  return { t, covered, fiNumber, coastNumber, target };
}

// ---- decumulation / post-FIRE drawdown engine ----
// runs a single real-return path: corpus depletes by inflation-adjusted expense each year
function _runPath(corpus, expense, rr, retireAge, endAge) {
  let bal = corpus;
  const s = [{ age: retireAge, v: corpus }];
  let dep = null;
  for (let age = retireAge + 1; age <= endAge; age++) {
    bal = bal * (1 + rr) - expense;
    if (bal <= 0 && dep === null) dep = age;
    s.push({ age, v: Math.max(0, bal) });
  }
  return { s, dep, final: Math.max(0, bal) };
}

function drawdownProject({ corpus, annualExpense, returnPct, inflationPct, retireAge, endAge }) {
  const rr = (1 + returnPct/100) / (1 + inflationPct/100) - 1;   // real return
  const med = _runPath(corpus, annualExpense, rr, retireAge, endAge);
  const hi  = _runPath(corpus, annualExpense, rr + 0.025, retireAge, endAge); // lucky sequence
  const lo  = _runPath(corpus, annualExpense, rr - 0.035, retireAge, endAge); // bad sequence
  const wr  = annualExpense / corpus * 100;                       // current withdrawal rate
  const lasts = med.dep === null;
  // success ≈ probability portfolio survives to endAge, driven by withdrawal rate + horizon
  let success = Math.round(99 - Math.max(0, wr - 2.6) * 17 - Math.max(0, (endAge - retireAge) - 45) * 0.35);
  if (!lasts) success = Math.min(success, 44);
  success = Math.max(3, Math.min(99, success));
  return { rr, med, hi, lo, wr, lasts, success, depleteAge: med.dep, legacy: med.final, retireAge, endAge };
}

Object.assign(window, { drawdownProject });

// ---- income tax: old vs new regime (FY 2025-26, salaried, < ₹50L so no surcharge) ----
const TAX_PROFILE = {
  gross: 2800000,           // CTC-adjusted gross salary
  basic: 1120000,           // 40% of gross — drives 80CCD(2) limit
  // old-regime deductions the user already claims
  ded80C: 150000, ded80D: 25000, homeLoanInt: 200000, nps80CCD1B: 50000,
};
function _slabTax(taxable, slabs) {
  let tax = 0;
  for (let i = 0; i < slabs.length; i++) {
    const [lo, hi, rate] = slabs[i];
    if (taxable > lo) tax += (Math.min(taxable, hi) - lo) * rate;
  }
  return tax;
}
const NEW_SLABS = [[0,400000,0],[400000,800000,.05],[800000,1200000,.10],[1200000,1600000,.15],[1600000,2000000,.20],[2000000,2400000,.25],[2400000,Infinity,.30]];
const OLD_SLABS = [[0,250000,0],[250000,500000,.05],[500000,1000000,.20],[1000000,Infinity,.30]];
function _withCess(t){ return Math.round(t * 1.04); }      // 4% health & education cess

function taxScenarios() {
  const p = TAX_PROFILE;
  const npsEmployer = Math.round(p.basic * 0.14);            // 80CCD(2): up to 14% of basic (new regime)
  // NEW regime — only standard deduction (₹75k) + optional 80CCD(2)
  const newTaxableBase = p.gross - 75000;
  const newTaxNoNps = _withCess(_slabTax(newTaxableBase, NEW_SLABS));
  const newTaxWithNps = _withCess(_slabTax(newTaxableBase - npsEmployer, NEW_SLABS));
  // OLD regime — standard deduction (₹50k) + chapter VI-A deductions
  const oldDeductions = 50000 + p.ded80C + p.ded80D + p.homeLoanInt + p.nps80CCD1B;
  const oldTaxable = p.gross - oldDeductions;
  const oldTax = _withCess(_slabTax(oldTaxable, OLD_SLABS));
  const best = Math.min(newTaxWithNps, oldTax);
  return {
    gross: p.gross, npsEmployer, oldDeductions,
    newTaxableBase, newTaxNoNps, newTaxWithNps, oldTaxable, oldTax,
    npsSaving: newTaxNoNps - newTaxWithNps,
    bestRegime: newTaxWithNps <= oldTax ? 'new' : 'old',
    bestTax: best, currentTax: newTaxNoNps,
    totalSaving: newTaxNoNps - best,
  };
}

Object.assign(window, { TAX_PROFILE, taxScenarios });

Object.assign(window, {
  fmtINR, fmtFull, USER, NETWORTH, SPEND, TXNS, CARDS, REWARDS, CATEGORIES, CAT_NOTE,
  rankCards, cardById, fireProject, FUNDS, TARGET_ALLOC, assetClass, portfolioStats,
  CARD_STATUS, cardMilestoneGap, cardsByUrgency, cardNudges, cardStatusOf, NEW_CARDS,
  TRACKED_MONTHLY, TRACKED_ANNUAL, FIRE_TYPES, fireTypeById, fireTypeTarget,
});
