// Insights — friendly-coach analysis of spending patterns.

const PageInsights = () => {
  const { state, derived, loadDemo } = useAppState();

  if (state.transactions.length === 0) {
    return (
      <div>
        <div className="topbar">
          <div>
            <h1 className="page-title">Insights</h1>
            <div className="page-sub">Personal coaching from your data</div>
          </div>
        </div>
        <div className="empty">
          <div className="empty-icon"><ISparkle size={22}/></div>
          <h3 className="serif" style={{fontSize:22}}>Add some data first</h3>
          <p>The more you track, the smarter the insights. Add a few transactions or load demo data to see this in action.</p>
          <button className="btn btn-primary" onClick={loadDemo}><IPlay size={13}/> Load demo data</button>
        </div>
      </div>
    );
  }

  const insights = generateInsights(state, derived);

  return (
    <div>
      <div className="topbar">
        <div>
          <h1 className="page-title">Your <span className="serif">insights</span></h1>
          <div className="page-sub">{insights.length} things we noticed</div>
        </div>
      </div>

      <CoachCard/>

      <div className="grid stagger" style={{gridTemplateColumns:'repeat(2, 1fr)', gap:16, marginTop:20}}>
        {insights.map((it, i) => {
          const Ico = it.icon || ISparkle;
          return (
            <div key={i} className="insight">
              <div className="insight-icon" style={{background: `var(--${it.tone}-soft)`, color:`var(--${it.tone}-deep, var(--${it.tone}))`}}>
                <Ico size={16}/>
              </div>
              <div className="row" style={{gap:6, marginBottom:8}}>
                <span className={`pill pill-${it.tone}`}>{it.label}</span>
                {it.amount != null && <span className="mono" style={{fontSize:11, color:'var(--ink-3)'}}>{fmtZARShort(it.amount)}</span>}
              </div>
              <div className="serif" style={{fontSize:18, lineHeight:1.3, letterSpacing:'-0.01em', marginBottom:8}}>{it.title}</div>
              <div style={{fontSize:13, color:'var(--ink-2)', lineHeight:1.55}}>{it.body}</div>
              {it.action && (
                <div style={{marginTop:14, padding:'10px 12px', background:'var(--surface-2)', borderRadius:10, fontSize:12.5, color:'var(--ink-2)'}}>
                  <strong style={{color:'var(--ink)'}}>Try this:</strong> {it.action}
                </div>
              )}
            </div>
          );
        })}
      </div>
    </div>
  );
};

function generateInsights(state, derived) {
  const out = [];
  const { months, categoryBreakdown, totalDebt, income, expense } = derived;
  const thisMo = months[months.length - 1] || { income: 0, expense: 0 };
  const prevMo = months[months.length - 2] || { income: 0, expense: 0 };

  // 1. Eating out warning
  const eatingOut = categoryBreakdown.find(c => c.id === 'eating-out');
  if (eatingOut && eatingOut.pct > 0.10) {
    out.push({
      icon: ICoffee, tone: 'coral', label: 'Watch this',
      title: `Eating out is ${(eatingOut.pct * 100).toFixed(0)}% of your spending`,
      body: `You're spending ${fmtZAR(eatingOut.amount, {cents:false})} a month on takeaways and restaurants. Even cutting that in half adds up to nearly ${fmtZARShort(eatingOut.amount * 6)} a year.`,
      action: 'Plan two "treat" meals per week and cook the rest. Most people save 40% without feeling deprived.',
      amount: eatingOut.amount,
    });
  }

  // 2. Spending dropped
  if (prevMo.expense && thisMo.expense < prevMo.expense * 0.95) {
    const diff = prevMo.expense - thisMo.expense;
    out.push({
      icon: ITrend, tone: 'mint', label: 'Nice work',
      title: `You're spending ${fmtZARShort(diff)} less than last month`,
      body: `That's a ${((diff/prevMo.expense)*100).toFixed(0)}% improvement. Whatever you changed, keep doing it.`,
      action: 'Send the difference straight to your emergency fund — pay yourself first.',
      amount: diff,
    });
  }

  // 3. Subscriptions creep
  const subs = categoryBreakdown.find(c => c.id === 'subscriptions');
  if (subs && subs.amount > 0) {
    out.push({
      icon: IBolt, tone: 'amber', label: 'Audit',
      title: `${fmtZAR(subs.amount, {cents:false})} a month going to subscriptions`,
      body: `That's ${fmtZARShort(subs.amount * 12)} a year. Most South Africans are on at least one streaming service they haven't watched in 60 days.`,
      action: 'Open your bank app, search "subscription" or "debit", and cancel anything you wouldn\'t pay for again today.',
      amount: subs.amount,
    });
  }

  // 4. Debt insight
  if (totalDebt > 0 && income > 0) {
    const ratio = totalDebt / (income * 12);
    if (ratio > 0.4) {
      out.push({
        icon: IDebt, tone: 'coral', label: 'Priority',
        title: 'Your debt is high vs income',
        body: `You owe ${fmtZARShort(totalDebt)} which is ${(ratio * 100).toFixed(0)}% of your annual income. The avalanche strategy could cut years off your payoff.`,
        action: 'Visit the Debt tracker — even an extra R 500/month makes a huge difference at high APRs.',
        amount: totalDebt,
      });
    }
  }

  // 5. Top category insight
  if (categoryBreakdown.length) {
    const top = categoryBreakdown[0];
    out.push({
      icon: ICat, tone: 'violet', label: 'Top category',
      title: `${top.label} is your biggest expense`,
      body: `${(top.pct * 100).toFixed(0)}% of your spending — ${fmtZAR(top.amount, {cents:false})} this month. Reducing this by even 10% would save you ${fmtZARShort(top.amount * 0.10 * 12)} a year.`,
      amount: top.amount,
    });
  }

  // 6. Savings rate
  const rate = income > 0 ? ((income - expense) / income) : 0;
  if (rate > 0.20) {
    out.push({
      icon: ISparkle, tone: 'mint', label: 'Excellent',
      title: `${(rate * 100).toFixed(0)}% savings rate`,
      body: `You're saving more than 1 in every 5 Rand you earn. At this pace you'll hit financial independence faster than most.`,
      action: "Don't let it sit in current account — move surplus to a 32-day notice account at 8%+.",
    });
  } else if (rate < 0.05 && income > 0) {
    out.push({
      icon: IInfo, tone: 'amber', label: 'Tighten up',
      title: 'You\'re saving less than 5%',
      body: 'Most experts recommend 15-20%. You don\'t need to get there overnight, but every percentage point compounds.',
      action: 'Pick the smallest category and cut it by 10% next month. Small wins build momentum.',
    });
  }

  // 7. Recurring weekend spend
  out.push({
    icon: IFire, tone: 'pink', label: 'Pattern',
    title: 'Most spending happens on weekends',
    body: 'Friday to Sunday is when budget-busting happens for most people. A R 200 Friday becomes R 800 by Sunday night.',
    action: 'Set a "weekend wallet" — withdraw a fixed amount on Friday and only spend that.',
  });

  return out.slice(0, 6);
}

Object.assign(window, { PageInsights, generateInsights });
