#!/bin/bash

# Create backup
cp telegram-bot.js telegram-bot.js.before-compact-fix

# Create the replacement function
cat > /tmp/new-showTaskList.js << 'EOFFUNCTION'
async function showTaskListFromData(ctx, tasks, title) {
  if (!tasks || tasks.length === 0) {
    return edit(ctx, `😔 <b>${title}</b>\n\nNo tasks available right now. Check back soon!`, Markup.inlineKeyboard([
      [Markup.button.callback('🔄 Refresh', 'tasks_all')],
      [Markup.button.callback('🔙 BACK', 'browse')],
    ]));
  }

  // Use compact format - show 20 tasks
  const msg = formatTaskListCompact(tasks, title.toLowerCase().replace(' ', '_')) + '\n\n💡 <i>Tap a number to view details</i>';
  
  // Create number buttons (1-20)
  const numberButtons = [];
  const displayCount = Math.min(tasks.length, 20);
  
  for (let i = 0; i < displayCount; i++) {
    if (i % 5 === 0) numberButtons.push([]);
    numberButtons[numberButtons.length - 1].push(
      Markup.button.callback(`${i + 1}`, `task_${tasks[i].id}`)
    );
  }
  
  numberButtons.push([
    Markup.button.callback('🔄 Refresh', 'tasks_all'),
    Markup.button.callback('🔙 BACK', 'browse')
  ]);
  
  await edit(ctx, msg, Markup.inlineKeyboard(numberButtons));
}
EOFFUNCTION

# Find the line number of the old function
LINE_START=$(grep -n "^async function showTaskListFromData" telegram-bot.js | cut -d: -f1)
LINE_END=$(awk -v start=$LINE_START 'NR>start && /^}$/ {print NR; exit}' telegram-bot.js)

# Replace the function
head -n $(($LINE_START - 1)) telegram-bot.js > /tmp/telegram-bot-new.js
cat /tmp/new-showTaskList.js >> /tmp/telegram-bot-new.js
tail -n +$(($LINE_END + 1)) telegram-bot.js >> /tmp/telegram-bot-new.js

# Replace the file
mv /tmp/telegram-bot-new.js telegram-bot.js

echo "✅ Function replaced successfully!"
echo "Original backed up to: telegram-bot.js.before-compact-fix"
EOFFUNCTION
