const fs = require('fs-extra');
const { getUserData } = require('./user');

async function sendMainMenu(sock, phone, name) {
  try {
    const companyData = await fs.readJson('config/company.json');
    const translations = await fs.readJson('config/translations.json');
    const userData = await getUserData(phone);
    const lang = userData.language || 'en';
    
    // Build menu message
    const menuMessage = translations[lang].welcome.replace('{name}', name || 'there').replace('{company}', companyData.name) + '\n\n' + translations[lang].main_menu;

    // Attempt to send message with image
    try {
      await sock.sendMessage(phone, {
        image: { url: companyData.logo },
        caption: menuMessage
      });
      console.log(`Sent main menu with logo to ${phone}`);
    } catch (imageError) {
      console.error(`Failed to send logo image for ${phone}:`, imageError.message);
      // Fallback to text-only message
      await sock.sendMessage(phone, { text: `${menuMessage}\n\n📷 (Note: Unable to load logo image.)` });
      console.log(`Sent text-only main menu to ${phone}`);
    }
  } catch (error) {
    console.error(`Error in sendMainMenu for ${phone}:`, error);
    await sock.sendMessage(phone, { text: '⚠️ *Oops!* Sorry, I encountered an error while loading the menu. 🙏 Please try again or type #startover. 🔄' });
  }
}

module.exports = { sendMainMenu };