/* Clear Mint — Financial Health · Recommendations. window.FHRecs */
(function () {
  const I = window.CMIcon;
  const useC = () => React.useContext(window.FHTheme);
  const { FHCard, FHChip, FHPill, FHBar, FHSegmented, FHLine, FHImpactMatrix, FHSpark, FHIcon } = window;
  const hexA = window.FHhexA;
  const money = n => '$' + Math.round(n).toLocaleString();

  /* live-AI hook: uses the in-app Claude bridge when present, else a graceful
     locally-composed coaching note (so it always answers). */
  function askAI(rec, base) {
    const prompt = 'In 2 short sentences, coach the user on this recommendation: "' + rec.title + '" \u2014 ' + rec.desc + ' Be specific and encouraging.';
    const ctx = 'Monthly surplus ' + money(base.netCashFlow) + '; card utilization ' + Math.round(base.utilization) + '%.';
    const local = rec.why + ' ' + rec.expected;
    // Route through the metered multi-provider endpoint (auth required). Falls back to the
    // locally-composed note on any failure (401/429/offline) so the UI always answers.
    const h = { 'Content-Type': 'application/json' };
    const tok = window.cmAuthToken ? window.cmAuthToken() : '';
    if (tok) h.Authorization = 'Bearer ' + tok;
    return fetch('/api/ai/route', { method: 'POST', headers: h, body: JSON.stringify({ taskClass: 'financial', question: prompt, context: ctx }) })
      .then(function (r) { return r.json(); })
      .then(function (d) { return (d && d.ok && d.text) ? d.text : local; })
      .catch(function () { return local; });
  }

  function Kpi({ label, value, valueColor, sub, icon, iconColor, spark }) {
    const C = useC();
    return React.createElement(FHCard, { pad: 18 },
      React.createElement('div', { style: { display: 'flex', alignItems: 'flex-start', justifyContent: 'space-between', gap: 10 } },
        React.createElement('div', { style: { minWidth: 0 } },
          React.createElement('div', { style: { fontSize: 12.5, color: C.sub, fontWeight: 700, display: 'flex', alignItems: 'center', gap: 5 } }, label, React.createElement(I.Info, { size: 13, style: { color: C.mut } })),
          React.createElement('div', { style: { fontFamily: 'var(--font-serif)', fontSize: 30, fontWeight: 700, color: valueColor || C.ink, marginTop: 8, lineHeight: 1 } }, value),
          sub ? React.createElement('div', { style: { fontSize: 11.5, color: C.sub, marginTop: 7 } }, sub) : null),
        icon ? React.createElement(FHChip, { name: icon, color: iconColor || C.emerald, size: 42, radius: 12 }) : null),
      spark ? React.createElement('div', { style: { marginTop: 6, height: 30 } }, React.createElement(FHSpark, { data: spark, color: C.emerald, h: 30 })) : null);
  }

  function RecCard({ r, base, expanded, onToggle }) {
    const C = useC();
    const col = r.impact === 'High' ? C.red : r.impact === 'Medium' ? C.amber : C.emerald;
    const [ai, setAi] = React.useState(null); const [loading, setLoading] = React.useState(false);
    const [state, setState] = React.useState(null); // accepted | dismissed | snoozed
    const doAsk = () => { setLoading(true); askAI(r, base).then(t => { setAi(t); setLoading(false); }).catch(() => { setAi(r.why + ' ' + r.expected); setLoading(false); }); };
    return React.createElement('div', { style: { borderBottom: '1px solid ' + C.line, opacity: state === 'dismissed' ? 0.5 : 1, transition: '.2s' } },
      React.createElement('div', { style: { display: 'grid', gridTemplateColumns: '46px 1fr auto', gap: 14, padding: '18px 4px', alignItems: 'start', cursor: 'pointer' }, onClick: onToggle },
        React.createElement(FHChip, { name: r.icon, color: r.color, size: 46, radius: 12 }),
        React.createElement('div', { style: { minWidth: 0 } },
          React.createElement('div', { style: { display: 'flex', alignItems: 'center', gap: 10, flexWrap: 'wrap' } },
            React.createElement('span', { style: { fontWeight: 800, fontSize: 15, color: C.ink } }, r.title),
            React.createElement(FHPill, { color: col }, r.impact + ' Impact')),
          React.createElement('div', { style: { fontSize: 13, color: C.sub, marginTop: 5, lineHeight: 1.5, maxWidth: 520 } }, r.desc),
          React.createElement('div', { style: { display: 'inline-flex', alignItems: 'center', gap: 5, marginTop: 9, fontSize: 12, fontWeight: 700, color: C.emerald } }, React.createElement('span', { style: { width: 5, height: 5, borderRadius: 9, background: C.emerald } }), r.improves)),
        React.createElement('div', { style: { textAlign: 'right', flexShrink: 0, display: 'flex', alignItems: 'center', gap: 14 } },
          React.createElement('div', null,
            React.createElement('div', { style: { fontSize: 11.5, color: C.sub, fontWeight: 600 } }, 'Potential Impact'),
            React.createElement('div', { className: 'num', style: { fontSize: 19, fontWeight: 800, color: C.emerald, marginTop: 2 } }, '+' + r.points + ' pts'),
            r.savings ? React.createElement('div', { className: 'num', style: { fontSize: 12.5, color: C.sub, marginTop: 2 } }, '+' + money(r.savings) + ' / year') : null),
          React.createElement(I.ChevR, { size: 16, style: { color: C.mut, transform: expanded ? 'rotate(90deg)' : 'none', transition: '.2s' } }))),
      expanded ? React.createElement('div', { style: { padding: '4px 4px 20px', display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 14 } , className: 'fh-2col'},
        React.createElement('div', { style: { background: C.panel2, border: '1px solid ' + C.line, borderRadius: 14, padding: 16 } },
          React.createElement('div', { style: { display: 'flex', alignItems: 'center', gap: 8, marginBottom: 12 } }, React.createElement(I.Spark, { size: 16, style: { color: C.gold } }), React.createElement('span', { style: { fontWeight: 800, fontSize: 13, color: C.ink } }, 'AI Coach')),
          [['Why this matters', r.why], ['Expected result', r.expected], ['Risk if ignored', r.risk]].map((row, i) =>
            React.createElement('div', { key: i, style: { marginBottom: 11 } },
              React.createElement('div', { style: { fontSize: 11, fontWeight: 800, color: C.sub, textTransform: 'uppercase', letterSpacing: '.04em', marginBottom: 3 } }, row[0]),
              React.createElement('div', { style: { fontSize: 12.5, color: C.ink, lineHeight: 1.55 } }, row[1]))),
          ai ? React.createElement('div', { style: { marginTop: 6, padding: '10px 12px', background: hexA(C.emerald, 0.1), border: '1px solid ' + hexA(C.emerald, 0.25), borderRadius: 10, fontSize: 12.5, color: C.ink, lineHeight: 1.55 } }, ai)
            : React.createElement('button', { onClick: doAsk, style: { marginTop: 4, display: 'inline-flex', alignItems: 'center', gap: 6, background: 'none', border: '1px solid ' + C.line2, color: C.emerald, borderRadius: 9, padding: '7px 12px', fontWeight: 700, fontSize: 12, cursor: 'pointer', fontFamily: 'inherit' } }, loading ? 'Thinking\u2026' : 'Ask Mint why')),
        React.createElement('div', { style: { display: 'flex', flexDirection: 'column', gap: 10 } },
          React.createElement('div', { style: { display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 10 } },
            [['Difficulty', r.difficulty], ['Time Required', r.time], ['Confidence', r.confidence + '%'], ['Annual Value', r.savings ? money(r.savings) : '\u2014']].map((m, i) =>
              React.createElement('div', { key: i, style: { background: C.panel2, border: '1px solid ' + C.line, borderRadius: 12, padding: '11px 13px' } },
                React.createElement('div', { style: { fontSize: 11, color: C.sub, fontWeight: 700 } }, m[0]),
                React.createElement('div', { className: 'num', style: { fontSize: 15, fontWeight: 800, color: C.ink, marginTop: 3 } }, m[1])))),
          React.createElement('div', { style: { display: 'flex', gap: 8, marginTop: 2, flexWrap: 'wrap' } },
            React.createElement('button', { onClick: () => setState('accepted'), style: { flex: 1, minWidth: 110, background: state === 'accepted' ? C.emDeep : C.emerald, color: '#fff', border: 0, borderRadius: 10, padding: '10px 12px', fontWeight: 800, fontSize: 12.5, cursor: 'pointer', fontFamily: 'inherit', display: 'inline-flex', alignItems: 'center', justifyContent: 'center', gap: 6 } }, React.createElement(I.Check, { size: 14 }), state === 'accepted' ? 'Added to plan' : r.action),
            React.createElement('button', { onClick: () => setState('snoozed'), style: { background: C.panel2, color: C.sub, border: '1px solid ' + C.line2, borderRadius: 10, padding: '10px 12px', fontWeight: 700, fontSize: 12.5, cursor: 'pointer', fontFamily: 'inherit' } }, 'Snooze'),
            React.createElement('button', { onClick: () => setState('dismissed'), style: { background: C.panel2, color: C.sub, border: '1px solid ' + C.line2, borderRadius: 10, padding: '10px 12px', fontWeight: 700, fontSize: 12.5, cursor: 'pointer', fontFamily: 'inherit' } }, 'Dismiss')))) : null);
  }

  function WhatIf({ base }) {
    const C = useC();
    const [v, setV] = React.useState({ mortgage: 100, invest: 100, save: 150, visa: 0, rrsp: 0 });
    const set = (k, val) => setV(s => Object.assign({}, s, { [k]: val }));
    const sliders = [
      { k: 'mortgage', label: 'Pay extra on mortgage', max: 1000, step: 50, unit: '/mo' },
      { k: 'invest', label: 'Invest more', max: 1000, step: 50, unit: '/mo' },
      { k: 'save', label: 'Save more', max: 1000, step: 50, unit: '/mo' },
      { k: 'visa', label: 'Pay off Visa', max: 100, step: 25, unit: '%' },
      { k: 'rrsp', label: 'Increase RRSP', max: 1000, step: 50, unit: '/mo' }
    ];
    const extra = v.mortgage + v.invest + v.save + v.rrsp;
    const futureScore = Math.min(110, 87 + Math.round((v.mortgage * 0.004 + v.invest * 0.006 + v.save * 0.008 + v.visa * 0.08 + v.rrsp * 0.005)));
    const nwImpact = Math.round((v.invest + v.save) * 12 * 5 * 1.07 + v.rrsp * 12 * 5 * 1.05);
    const debtFree = 2027 - Math.round(v.mortgage / 250) - Math.round(v.visa / 50);
    const retire = 60 - Math.round((v.invest + v.rrsp) / 300);
    const outs = [
      { label: 'Future Score', value: futureScore, color: C.emerald },
      { label: 'Net Worth Impact', value: '+' + money(nwImpact), color: C.emerald },
      { label: 'Debt-Free Date', value: 'Dec ' + Math.max(2024, debtFree), color: C.gold },
      { label: 'Retirement Age', value: Math.max(52, retire), color: C.blue }
    ];
    return React.createElement(FHCard, { title: 'What-If Simulator', info: true, right: React.createElement('span', { style: { fontSize: 11.5, color: C.sub, fontWeight: 600 } }, 'Drag to model your future') },
      React.createElement('div', { style: { display: 'grid', gridTemplateColumns: '1.2fr 1fr', gap: 22 }, className: 'fh-2col' },
        React.createElement('div', { style: { display: 'flex', flexDirection: 'column', gap: 15 } },
          sliders.map(s => React.createElement('div', { key: s.k },
            React.createElement('div', { style: { display: 'flex', justifyContent: 'space-between', marginBottom: 7 } },
              React.createElement('span', { style: { fontSize: 12.5, color: C.ink, fontWeight: 600 } }, s.label),
              React.createElement('span', { className: 'num', style: { fontSize: 12.5, color: C.emerald, fontWeight: 800 } }, (s.unit === '%' ? '' : '$') + v[s.k] + s.unit)),
            React.createElement('input', { type: 'range', min: 0, max: s.max, step: s.step, value: v[s.k], onChange: e => set(s.k, +e.target.value),
              style: { width: '100%', accentColor: C.emerald, height: 5, cursor: 'pointer' } }))),
          React.createElement('div', { style: { fontSize: 11.5, color: C.mut, marginTop: 2 } }, 'Committing ' + money(extra) + '/mo across these moves.')),
        React.createElement('div', { style: { display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 12, alignContent: 'start' } },
          outs.map((o, i) => React.createElement('div', { key: i, style: { background: C.panel2, border: '1px solid ' + C.line, borderRadius: 14, padding: '16px 16px' } },
            React.createElement('div', { style: { fontSize: 11.5, color: C.sub, fontWeight: 700 } }, o.label),
            React.createElement('div', { className: 'num', style: { fontFamily: 'var(--font-serif)', fontSize: 26, fontWeight: 700, color: o.color, marginTop: 6 } }, o.value))))));
  }

  function FHRecs({ data }) {
    const C = useC();
    const recs = data.recommendations, k = data.kpis;
    const [filter, setFilter] = React.useState('All');
    const [sort, setSort] = React.useState('Impact (High to Low)');
    const [open, setOpen] = React.useState(recs[0].id);
    const counts = { High: recs.filter(r => r.impact === 'High').length, Medium: recs.filter(r => r.impact === 'Medium').length, Low: recs.filter(r => r.impact === 'Low').length };
    let list = recs.filter(r => filter === 'All' || r.impact === filter.split(' ')[0]);
    if (sort.indexOf('Savings') === 0) list = list.slice().sort((a, b) => b.savings - a.savings);
    else list = list.slice().sort((a, b) => b.points - a.points);
    const plan = recs.slice(0, 5);
    const proj = k.projection;
    const matrixPts = recs.map((r, i) => ({ n: i + 1, effort: r.difficulty === 'Easy' ? 25 : r.difficulty === 'Medium' ? 60 : 85, impact: r.impact === 'High' ? 82 : r.impact === 'Medium' ? 55 : 28, color: r.impact === 'High' ? C.red : r.impact === 'Medium' ? C.amber : C.emerald, size: 11 + r.points }));

    return React.createElement('div', { style: { display: 'flex', flexDirection: 'column', gap: 18 } },
      /* KPIs */
      React.createElement('div', { style: { display: 'grid', gridTemplateColumns: 'repeat(4,1fr)', gap: 14 }, className: 'fh-kpi4' },
        React.createElement(Kpi, { label: 'Total Potential Improvement', value: '+' + k.potentialPoints + ' pts', valueColor: C.emerald, sub: 'to your Financial Health Score', spark: data.score.history.slice(-7) }),
        React.createElement(Kpi, { label: 'Potential Annual Impact', value: money(k.potentialSavings), valueColor: C.emerald, sub: 'in potential savings & growth', icon: 'Wallet', iconColor: C.emerald }),
        React.createElement(Kpi, { label: 'Recommendations', value: k.count, sub: 'active recommendations', icon: 'Reports', iconColor: C.gold }),
        React.createElement(Kpi, { label: 'High Impact Actions', value: k.highPriority, sub: 'priority actions to focus on', icon: 'Goals', iconColor: C.red })),
      /* filters */
      React.createElement('div', { style: { display: 'flex', alignItems: 'center', justifyContent: 'space-between', gap: 12, flexWrap: 'wrap' } },
        React.createElement(FHSegmented, { value: filter, onChange: setFilter, options: [{ v: 'All', l: 'All (' + recs.length + ')' }, { v: 'High Impact', l: 'High (' + counts.High + ')' }, { v: 'Medium Impact', l: 'Medium (' + counts.Medium + ')' }, { v: 'Low Impact', l: 'Low (' + counts.Low + ')' }] }),
        React.createElement('div', { style: { display: 'flex', alignItems: 'center', gap: 8 } }, React.createElement('span', { style: { fontSize: 12.5, color: C.sub, fontWeight: 600 } }, 'Sort by:'), React.createElement(window.FHSelect, { options: ['Impact (High to Low)', 'Savings (High to Low)'], value: sort, onChange: setSort }))),
      /* main grid */
      React.createElement('div', { style: { display: 'grid', gridTemplateColumns: '1.6fr 1fr', gap: 16, alignItems: 'start' }, className: 'fh-2col' },
        React.createElement(FHCard, { pad: 16 }, list.map(r => React.createElement(RecCard, { key: r.id, r, base: data.base, expanded: open === r.id, onToggle: () => setOpen(open === r.id ? null : r.id) }))),
        React.createElement('div', { style: { display: 'flex', flexDirection: 'column', gap: 16 } },
          React.createElement(FHCard, { title: 'Recommended Action Plan', info: true },
            React.createElement('div', { style: { display: 'flex', flexDirection: 'column', gap: 2 } },
              plan.map((r, i) => React.createElement('div', { key: r.id, style: { display: 'flex', alignItems: 'center', gap: 12, padding: '11px 0', borderBottom: i < plan.length - 1 ? '1px solid ' + C.line : 'none' } },
                React.createElement('span', { style: { width: 24, height: 24, borderRadius: 999, background: hexA(r.color, 0.16), color: r.color, fontSize: 11, fontWeight: 800, display: 'flex', alignItems: 'center', justifyContent: 'center', flexShrink: 0 } }, i + 1),
                React.createElement('div', { style: { flex: 1, minWidth: 0 } }, React.createElement('div', { style: { fontWeight: 700, fontSize: 13, color: C.ink } }, r.title), React.createElement('div', { style: { fontSize: 11.5, color: C.sub, marginTop: 1 } }, r.action)),
                React.createElement('span', { className: 'num', style: { fontSize: 13, fontWeight: 800, color: C.emerald } }, '+' + r.points + ' pts')))),
            React.createElement('button', { style: { width: '100%', marginTop: 12, background: C.panel2, border: '1px solid ' + C.line, borderRadius: 11, padding: '11px', color: C.emerald, fontWeight: 800, fontSize: 12.5, cursor: 'pointer', fontFamily: 'inherit', display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 5 } }, 'View full action plan', React.createElement(I.ChevR, { size: 14 }))),
          React.createElement(FHCard, { title: 'Potential Improvement Over Time', info: true },
            React.createElement('div', { style: { fontSize: 12, color: C.sub, marginBottom: 10 } }, 'Your score if you complete all recommendations'),
            React.createElement(FHLine, { height: 180, x: proj.labels, series: [{ name: 'Projected', data: proj.points, color: C.emerald, dots: true }], yFmt: v => v }),
            React.createElement('div', { style: { display: 'flex', justifyContent: 'space-between', marginTop: 8, fontSize: 12 } },
              React.createElement('span', { style: { color: C.sub } }, 'Current ', React.createElement('b', { style: { color: C.ink } }, proj.now)),
              React.createElement('span', { style: { color: C.sub } }, 'Potential ', React.createElement('b', { style: { color: C.emerald } }, proj.optimized)))))),
      /* what-if */
      React.createElement(WhatIf, { base: data.base }),
      /* impact matrix */
      React.createElement('div', { style: { display: 'grid', gridTemplateColumns: '1.3fr 1fr', gap: 16 }, className: 'fh-2col' },
        React.createElement(FHCard, { title: 'Impact Matrix', info: true, right: React.createElement('span', { style: { fontSize: 11.5, color: C.sub } }, 'Effort vs impact') },
          React.createElement(FHImpactMatrix, { points: matrixPts, height: 300 }),
          React.createElement('div', { style: { display: 'flex', gap: 14, flexWrap: 'wrap', marginTop: 6 } }, recs.slice(0, 6).map((r, i) => React.createElement('span', { key: i, style: { fontSize: 11, color: C.sub, display: 'inline-flex', alignItems: 'center', gap: 5 } }, React.createElement('span', { style: { width: 14, height: 14, borderRadius: 999, background: r.impact === 'High' ? C.red : r.impact === 'Medium' ? C.amber : C.emerald, color: '#fff', fontSize: 9, fontWeight: 800, display: 'inline-flex', alignItems: 'center', justifyContent: 'center' } }, i + 1), r.title)))),
        React.createElement(FHCard, { title: 'Opportunity Funnel', info: true },
          React.createElement('div', { style: { display: 'flex', flexDirection: 'column', gap: 10, marginTop: 4 } },
            [['Detected Opportunities', recs.length + 4, 100, C.blue], ['Recommended Actions', recs.length, 72, C.emerald], ['Added to Plan', 5, 45, C.gold], ['Completed', 1, 12, C.teal]].map((f, i) =>
              React.createElement('div', { key: i },
                React.createElement('div', { style: { display: 'flex', justifyContent: 'space-between', fontSize: 12.5, marginBottom: 5 } }, React.createElement('span', { style: { color: C.ink, fontWeight: 600 } }, f[0]), React.createElement('span', { className: 'num', style: { color: C.ink, fontWeight: 800 } }, f[1])),
                React.createElement(FHBar, { pct: f[2], color: f[3], height: 10 })))))),
      /* banner */
      React.createElement('div', { style: { display: 'flex', alignItems: 'center', justifyContent: 'space-between', gap: 16, background: C.name === 'dark' ? hexA(C.emerald, 0.1) : '#0F3D2C', border: '1px solid ' + hexA(C.emerald, 0.3), borderRadius: 16, padding: '20px 24px', flexWrap: 'wrap' } },
        React.createElement('div', { style: { display: 'flex', alignItems: 'center', gap: 14 } },
          React.createElement('span', { style: { width: 44, height: 44, borderRadius: 12, background: hexA(C.emerald, 0.2), color: C.emerald, display: 'flex', alignItems: 'center', justifyContent: 'center' } }, React.createElement(I.Goals, { size: 22 })),
          React.createElement('div', null, React.createElement('div', { style: { fontWeight: 800, fontSize: 15, color: C.name === 'dark' ? C.ink : '#fff' } }, 'Want a personalized plan?'), React.createElement('div', { style: { fontSize: 13, color: C.name === 'dark' ? C.sub : 'rgba(255,255,255,.7)', marginTop: 2 } }, 'Get a custom roadmap based on your goals, income and spending habits.'))),
        React.createElement('button', { onClick: () => { location.hash = '#/ai'; }, style: { background: C.emerald, color: '#06291B', border: 0, borderRadius: 11, padding: '12px 20px', fontWeight: 800, fontSize: 13.5, cursor: 'pointer', fontFamily: 'inherit', display: 'inline-flex', alignItems: 'center', gap: 7 } }, 'Create My Plan', React.createElement(I.ChevR, { size: 15 }))));
  }
  window.FHRecs = FHRecs;
})();
