const express = require('express');
const puppeteer = require('puppeteer');
const fs = require('fs');
const path = require('path');
const bodyParser = require('body-parser');

const app = express();
const PORT = 3001;

app.use(bodyParser.json());

// Buat folder sesi kalau belum ada
if (!fs.existsSync(path.join(__dirname, 'sessions'))) {
  fs.mkdirSync(path.join(__dirname, 'sessions'));
}

app.post('/comment', async (req, res) => {
  const { ig_username, ig_password, post_url, comment } = req.body;
  console.log('📦 Payload diterima:', req.body);
  const SESSION_FILE_PATH = path.join(__dirname, 'sessions', `${ig_username}.json`);

  try {
    const browser = await puppeteer.launch({
      headless: true,
      args: ['--no-sandbox', '--disable-setuid-sandbox']
    });

    const page = await browser.newPage();
    await page.setUserAgent('Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36');
    await page.setViewport({ width: 1280, height: 800 });

    let loggedIn = false;
    if (fs.existsSync(SESSION_FILE_PATH)) {
      const cookies = JSON.parse(fs.readFileSync(SESSION_FILE_PATH));
      await page.setCookie(...cookies);
      console.log('✅ Sesi login dimuat');
    }

    await page.goto('https://www.instagram.com/', { waitUntil: 'networkidle2' });
    await new Promise(resolve => setTimeout(resolve, 3000));

    loggedIn = await page.evaluate(() => {
      return !!document.querySelector('svg[aria-label="Beranda"], svg[aria-label="Home"]');
    });

    if (!loggedIn) {
      console.log('🔐 Login ulang...');
      await page.goto('https://www.instagram.com/accounts/login/', { waitUntil: 'networkidle2' });

      await page.waitForSelector('input[name="username"]', { timeout: 15000 });
      await page.type('input[name="username"]', ig_username, { delay: 100 });
      await page.type('input[name="password"]', ig_password, { delay: 100 });
      await page.keyboard.press('Enter');

      await page.waitForNavigation({ waitUntil: 'networkidle2', timeout: 15000 }).catch(() => {});
      await new Promise(resolve => setTimeout(resolve, 4000));

      if (page.url().includes('/onetap')) {
        console.log('🔁 Redirect dari Instagram One Tap, alihkan ke beranda...');
        await page.goto('https://www.instagram.com/', { waitUntil: 'networkidle2' });
        await new Promise(resolve => setTimeout(resolve, 3000));
      }

      const loginFailed = await page.evaluate(() => {
        return (
          document.body.innerText.includes('kata sandi Anda salah') ||
          document.body.innerText.includes('Your password was incorrect') ||
          document.body.innerText.includes('Try again')
        );
      });

      if (loginFailed) {
        throw new Error('Login gagal: username atau password salah');
      }

      const cookies = await page.cookies();
      fs.writeFileSync(SESSION_FILE_PATH, JSON.stringify(cookies, null, 2));
      console.log('💾 Sesi login disimpan');
    }

    // Kunjungi postingan
    await page.goto(post_url, { waitUntil: 'networkidle2' });
    await new Promise(resolve => setTimeout(resolve, 3000));

    await page.evaluate(() => window.scrollBy(0, window.innerHeight));
    await new Promise(resolve => setTimeout(resolve, 2000));

    await page.screenshot({ path: 'debug_screenshot.png', fullPage: true });

    const commentBoxSelector = 'form textarea';
    await page.waitForSelector(commentBoxSelector, { timeout: 15000 });

    await page.click(commentBoxSelector);
    await page.type(commentBoxSelector, comment, { delay: 50 });

    await new Promise(resolve => setTimeout(resolve, 2000));
    await page.keyboard.press('Enter');

    console.log('✅ Berhasil mengirim komentar!');
    res.json({ success: true, message: '✅ Berhasil mengirim komentar!' });
    await browser.close();
  } catch (error) {
    console.error('❌ ERROR:', error);
    res.status(500).json({ success: false, message: 'Gagal kirim komentar', error: error.message });
  }
});

// 🔴 ENDPOINT REPORT
app.post('/report', async (req, res) => {
  const { ig_username, ig_password, target_username } = req.body;
  console.log('🛑 Menerima request report:', req.body);
  const SESSION_FILE_PATH = path.join(__dirname, 'sessions', `${ig_username}.json`);

  let browser;
  let page;

  try {
    browser = await puppeteer.launch({
      headless: false,
      args: ['--no-sandbox', '--disable-setuid-sandbox']
    });

    page = await browser.newPage();
    await page.setUserAgent('Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36');
    await page.setViewport({ width: 1280, height: 800 });

    if (fs.existsSync(SESSION_FILE_PATH)) {
      const cookies = JSON.parse(fs.readFileSync(SESSION_FILE_PATH));
      await page.setCookie(...cookies);
      console.log('✅ Sesi login dimuat');
    }

    await page.goto('https://www.instagram.com/', { waitUntil: 'networkidle2' });
    await new Promise(resolve => setTimeout(resolve, 3000));

    const loggedIn = await page.evaluate(() => {
      return !!document.querySelector('svg[aria-label="Beranda"], svg[aria-label="Home"]');
    });

    if (!loggedIn) {
      console.log('🔐 Login ulang...');
      await page.goto('https://www.instagram.com/accounts/login/', { waitUntil: 'networkidle2' });

      await page.waitForSelector('input[name="username"]', { timeout: 15000 });
      await page.type('input[name="username"]', ig_username, { delay: 100 });
      await page.type('input[name="password"]', ig_password, { delay: 100 });
      await page.keyboard.press('Enter');

      await page.waitForNavigation({ waitUntil: 'networkidle2', timeout: 15000 }).catch(() => {});
      await new Promise(resolve => setTimeout(resolve, 4000));

      if (page.url().includes('/onetap')) {
        await page.goto('https://www.instagram.com/', { waitUntil: 'networkidle2' });
        await new Promise(resolve => setTimeout(resolve, 3000));
      }

      const loginFailed = await page.evaluate(() => {
        return (
          document.body.innerText.includes('kata sandi Anda salah') ||
          document.body.innerText.includes('Your password was incorrect') ||
          document.body.innerText.includes('Try again')
        );
      });

      if (loginFailed) {
        throw new Error('Login gagal: username atau password salah');
      }

      const cookies = await page.cookies();
      fs.writeFileSync(SESSION_FILE_PATH, JSON.stringify(cookies, null, 2));
      console.log('💾 Sesi login disimpan');
    }

    // Kunjungi profil target
    await page.goto(`https://www.instagram.com/${target_username}/`, { waitUntil: 'networkidle2' });
    await new Promise(resolve => setTimeout(resolve, 3000));

    // Klik ikon "Options"
    const optionsButton = await page.$('svg[aria-label="Options"]');
    if (!optionsButton) {
      throw new Error('Tidak menemukan ikon "Options"');
    }
    await optionsButton.evaluate(el => el.parentElement.click());
    console.log('📌 Ikon "Options" diklik');

    // Klik "Report"
    await page.waitForSelector('div[role="dialog"] button');
    await clickButtonByText(page, ['report', 'laporkan']);

    // Klik "Report Account"
    await page.waitForSelector('div[role="dialog"] button');
    await clickButtonByText(page, ['report account', 'laporkan akun']);

    // Klik "It’s pretending to be someone else"
    await page.waitForSelector('div[role="dialog"] button');
    await clickButtonByText(page, ['pretending to be someone else', 'menyamar sebagai orang lain']);

    // Klik "A celebrity or public figure"
    await page.waitForSelector('div[role="dialog"]');
await clickRadioOptionByText(page, ['Someone I follow', 'seseorang yang saya ikuti']);



    // Klik Submit
    await page.waitForSelector('div[role="dialog"] button');
    await clickButtonByText(page, ['submit report', 'kirim laporan', 'done', 'selesai']);

    // Tambahan untuk memilih akun yang ditiru
await page.waitForSelector('input[placeholder]', { timeout: 10000 });
await page.type('input[placeholder]', 'zaidan_yahyaa', { delay: 100 });
console.log('⌨️ Mengetik "zaidan_yahyaa" di kolom pencarian');

await new Promise(resolve => setTimeout(resolve, 3000));

// Tunggu tombol "Next" muncul di manapun
await page.waitForFunction(() => {
  const buttons = Array.from(document.querySelectorAll('button'));
  return buttons.some(btn => btn.innerText.trim().toLowerCase() === 'next');
}, { timeout: 10000 });

const allButtons = await page.$$('button');
let clicked = false;

for (const btn of allButtons) {
  const text = await btn.evaluate(el => el.innerText.trim().toLowerCase());
  if (text === 'next') {
    await btn.click();
    clicked = true;
    console.log('➡️ Klik tombol "Next" setelah mengetik username');
    break;
  }
}

if (!clicked) {
  throw new Error('❌ Tidak menemukan tombol "Next" setelah mengetik username');
}

// Tunggu agar kamu bisa lihat hasil
await new Promise(resolve => setTimeout(resolve, 60000));



// Klik tombol Block <username>
// await page.waitForSelector('div[role="dialog"] button');
// await clickButtonByText(page, [
//   `Block ${target_username}`,
//   `Blokir ${target_username}`
// ]);

// await page.waitForSelector('div[role="dialog"] button');
// await clickButtonByText(page, ['Block', 'Blokir']);

// // ✅ Tunggu dan klik tombol "Dismiss" untuk menutup modal
// await page.waitForSelector('div[role="dialog"] button');
// await clickButtonByText(page, ['Dismiss', 'Tutup']);

// console.log(`📌 Akun ${target_username} berhasil diblokir`);

    console.log('✅ Pelaporan berhasil!');
    res.json({ success: true, message: '✅ Pelaporan berhasil!' });

    // await browser.close();
  } catch (error) {
    console.error('❌ ERROR REPORT:', error);
    if (page) {
      await page.screenshot({ path: 'report_error.png', fullPage: true }).catch(() => {});
    }
    if (browser) await browser.close();
    res.status(500).json({ success: false, message: 'Gagal melakukan report', error: error.message });
  }
});

// Fungsi bantu klik tombol berdasarkan teks
async function clickButtonByText(page, texts, retries = 5) {
  texts = texts.map(t => t.toLowerCase());

  for (let attempt = 0; attempt < retries; attempt++) {
    const buttons = await page.$$('div[role="dialog"] button');
    for (const btn of buttons) {
      const text = await (await btn.getProperty('innerText')).jsonValue();
      if (text && texts.some(t => text.toLowerCase().includes(t))) {
        await btn.click();
        await new Promise(r => setTimeout(r, 1000));
        console.log(`📌 Klik tombol: ${text}`);
        return;
      }
    }

    // Tunggu sebentar sebelum mencoba lagi
    await new Promise(r => setTimeout(r, 2000));
  }

  throw new Error(`Tombol dengan teks [${texts.join(', ')}] tidak ditemukan`);
}

async function clickRadioOptionByText(page, texts) {
  texts = texts.map(t => t.trim().toLowerCase());

  // Ambil semua div yang berisi teks opsi
  const radioElements = await page.$$('div[role="dialog"] div._abn2');

  console.log(`🔍 Ditemukan ${radioElements.length} kandidat elemen opsi`);

  for (const el of radioElements) {
    const text = await (await el.getProperty('innerText')).jsonValue();
    const cleanText = text.trim().toLowerCase();

    console.log('🪪 Opsi:', cleanText);

    if (texts.includes(cleanText)) {
      await el.click();
      console.log(`📌 Opsi radio dipilih: ${text}`);
      return;
    }
  }

  throw new Error(`Opsi radio dengan teks [${texts.join(', ')}] tidak ditemukan`);
}




app.listen(PORT, () => {
  console.log(`🚀 Bot berjalan di http://localhost:${PORT}`);
});
