async function generateUpgradePitch(supabase, userId, currentScanResults) {
  // Fetch prior scan sessions + picks
  const { data: sessions } = await supabase
    .from('scan_sessions')
    .select('id, final_grade, legs, created_at')
    .eq('user_id', userId)
    .order('created_at', { ascending: false })
    .limit(10);

  const { data: picks } = await supabase
    .from('picks')
    .select('stat_type, direction, grade, player')
    .eq('user_id', userId)
    .order('created_at', { ascending: false })
    .limit(50);

  const allPicks = picks || [];
  const allSessions = sessions || [];
  const totalScans = allSessions.length + 1; // +1 for current

  // Count good grades (A or B)
  const priorGrades = allSessions.map((s) => s.final_grade).filter(Boolean);
  if (currentScanResults?.grade) priorGrades.push(currentScanResults.grade);
  const goodCount = priorGrades.filter((g) => g === 'A' || g === 'B').length;

  // Most common stat type
  const statCounts = {};
  for (const pick of allPicks) {
    statCounts[pick.stat_type] = (statCounts[pick.stat_type] || 0) + 1;
  }
  // Include current scan legs
  if (currentScanResults?.legs) {
    for (const leg of currentScanResults.legs) {
      const st = leg.stat_type;
      statCounts[st] = (statCounts[st] || 0) + 1;
    }
  }
  const topStatType = Object.entries(statCounts).sort((a, b) => b[1] - a[1])[0]?.[0] || 'props';

  // Most common direction for top stat
  const dirCounts = { over: 0, under: 0 };
  for (const pick of allPicks) {
    if (pick.stat_type === topStatType) {
      dirCounts[pick.direction] = (dirCounts[pick.direction] || 0) + 1;
    }
  }
  const topDirection = dirCounts.over >= dirCounts.under ? 'over' : 'under';

  // Average leg count
  const legCounts = allSessions.map((s) => (s.legs || []).length);
  if (currentScanResults?.legs) legCounts.push(currentScanResults.legs.length);
  const avgLegs = legCounts.length > 0
    ? legCounts.reduce((a, b) => a + b, 0) / legCounts.length
    : 3;

  // Unique players scanned
  const uniquePlayers = new Set(allPicks.map((p) => p.player));

  // Compliment
  let compliment;
  if (goodCount >= 3) compliment = "you've got a good eye";
  else if (goodCount >= 2) compliment = "you're getting sharper";
  else if (goodCount >= 1) compliment = "VYNDR is helping you filter";
  else compliment = "let's find better edges together";

  // Tier recommendation
  const tierRecommended = (avgLegs > 4 || uniquePlayers.size >= 5) ? 'desk' : 'analyst';

  const tierBenefit = tierRecommended === 'desk'
    ? 'Desk tier adds full bet tracking, ROI analytics, and priority cascade alerts.'
    : 'Analyst tier gives you unlimited reads plus line movement alerts so you never miss a soft number.';

  const founderPrice = tierRecommended === 'desk' ? '$34.99/mo' : '$14.99/mo';
  const standardPrice = tierRecommended === 'desk' ? '$49.99/mo' : '$19.99/mo';

  return {
    hook: `You've read ${totalScans} parlays this month. ${goodCount} graded B or higher — ${compliment}.`,
    insight: `Your best edge has been ${topStatType} ${topDirection}s. ${tierBenefit}`,
    cta: `Unlock unlimited reads for ${founderPrice} (founder rate)`,
    tier_recommended: tierRecommended,
    founder_price: founderPrice,
    standard_price: standardPrice,
  };
}

module.exports = { generateUpgradePitch };
