Welcome! Share code as fast as possible.

;(async function () {
  const BATCH_SIZE = 10
  const PAUSE_DURATION = 22000  // 22s pause between batches to avoid rate limit
  const DELAY = (ms) => new Promise(r => setTimeout(r, ms))

  // Minimal click — just mousedown + mouseup + click (prevents double-toggle bug)
  const softClick = (el) => {
    el.dispatchEvent(new MouseEvent('mousedown', { bubbles: true, cancelable: true }))
    el.dispatchEvent(new MouseEvent('mouseup',   { bubbles: true, cancelable: true }))
    el.dispatchEvent(new MouseEvent('click',     { bubbles: true, cancelable: true }))
  }

  // Full React-compatible click for buttons (not checkboxes)
  const reactClick = (el) => {
    el.dispatchEvent(new MouseEvent('mouseover', { bubbles: true }))
    softClick(el)
  }

  const waitFor = async (fn, maxWait = 8000) => {
    const start = Date.now()
    while (Date.now() - start < maxWait) {
      const el = fn()
      if (el) return el
      await DELAY(300)
    }
    return null
  }

  // Find Select button purely by text — NOT fragile CSS class names
  const findSelectBtn = () => {
    for (const span of document.querySelectorAll('span')) {
      if (span.textContent.trim() === 'Select') {
        let el = span
        while (el && el.tagName !== 'BODY') {
          if (el.getAttribute('role') === 'button' || el.tagName === 'BUTTON') return el
          el = el.parentElement
        }
        return span.parentElement
      }
    }
    return null
  }

  // Auto-dismiss rate limit / error popups
  const dialogDismisser = setInterval(() => {
    const okBtn = [...document.querySelectorAll('button, div[role="button"]')]
      .find(b => b.innerText?.trim() === 'OK')
    if (okBtn) { console.log('⚠️ Dismissed error dialog'); reactClick(okBtn) }
  }, 1000)

  let totalDeleted = 0

  while (true) {
    // --- Step 1: Click "Select" ---
    const selectBtn = await waitFor(findSelectBtn, 6000)
    if (!selectBtn) {
      console.log(`✅ Done! Total deleted: ${totalDeleted}`)
      break
    }
    reactClick(selectBtn)
    await DELAY(1800)

    // --- Step 2: Gather selectable items (try multiple aria-labels) ---
    let items = [...document.querySelectorAll('[aria-label="Toggle checkbox"]')]
    if (items.length === 0) items = [...document.querySelectorAll('[aria-label="Image with button"]')]
    if (items.length === 0) {
      // Try finding comment cards generically
      items = [...document.querySelectorAll('div[role="checkbox"]')]
    }

    if (items.length === 0) {
      console.log(`✅ No more comments found. Total deleted: ${totalDeleted}`)
      break
    }

    const batch = items.slice(0, BATCH_SIZE)
    console.log(`🗑️ Selecting ${batch.length} of ${items.length} comments...`)

    // --- Step 3: Click each checkbox ONCE, verify it's checked ---
    for (const item of batch) {
      // Check if already selected (avoid double-toggle bug)
      const alreadyChecked =
        item.getAttribute('aria-checked') === 'true' ||
        item.getAttribute('data-checked') === 'true' ||
        item.classList.contains('checked')

      if (!alreadyChecked) {
        softClick(item)
        await DELAY(350)
      }
    }

    await DELAY(1500)

    // --- Step 4: Find Delete button ---
    const deleteBtn = await waitFor(() => {
      // First try aria-label
      const byLabel = document.querySelector('[aria-label="Delete"]')
      if (byLabel) return byLabel
      // Fallback: find by text, but exclude "Delete account" etc.
      return [...document.querySelectorAll('button, div[role="button"], span')]
        .find(el => el.innerText?.trim() === 'Delete' && el.offsetParent !== null)
    }, 6000)

    if (!deleteBtn) {
      console.error('❌ Delete button not found — pausing to retry next batch')
      // Press Escape to exit select mode and retry
      document.dispatchEvent(new KeyboardEvent('keydown', { key: 'Escape', bubbles: true }))
      await DELAY(2000)
      continue
    }
    reactClick(deleteBtn)
    await DELAY(1200)

    // --- Step 5: Confirm deletion in dialog ---
    const confirmBtn = await waitFor(() =>
      [...document.querySelectorAll('button, div[role="button"]')]
        .find(b => {
          const txt = b.innerText?.trim()
          // Confirm button says "Delete" inside a dialog/sheet
          return txt === 'Delete' && b.closest('[role="dialog"], [role="alertdialog"], ._a9-_')
        })
    , 6000)

    if (!confirmBtn) {
      console.error('❌ Confirm dialog not found')
      break
    }
    reactClick(confirmBtn)

    await DELAY(2500)
    totalDeleted += batch.length
    console.log(`✔️ ${totalDeleted} deleted so far — waiting ${PAUSE_DURATION / 1000}s...`)
    await DELAY(PAUSE_DURATION)
    console.log('▶️ Resuming next batch...')
  }

  clearInterval(dialogDismisser)
  console.log(`🎉 Script complete. Total comments deleted: ${totalDeleted}`)
})()