import { chromium } from 'playwright'
import path from 'node:path'
import { fileURLToPath } from 'node:url'

const __dirname = path.dirname(fileURLToPath(import.meta.url))
const OUT = path.resolve(__dirname, '..', 'public', 'screenshots')

const APP = 'https://admin.food-market.kz'
const EMAIL = 'admin@food-market.local'
const PASSWORD = 'Admin12345!'

const browser = await chromium.launch({ headless: true })
const ctx = await browser.newContext({ ignoreHTTPSErrors: true, viewport: { width: 1600, height: 1000 } })
const page = await ctx.newPage()

console.log('login →', APP)
await page.goto(`${APP}/login`, { waitUntil: 'networkidle' })
await page.fill('input[type="email"]', EMAIL)
await page.fill('input[type="password"]', PASSWORD)
await page.click('button[type="submit"]')
await page.waitForURL((u) => !u.pathname.startsWith('/login'), { timeout: 30000 })
await page.waitForTimeout(1500)
console.log('logged in →', page.url())

// Override tenant: переходим на /super-admin/organizations → клик «Открыть»
// у строки FOOD MARKET (иконка-стрелка, title=«Открыть как…»).
console.log('tenant override → FOOD MARKET')
await page.goto(`${APP}/super-admin/organizations`, { waitUntil: 'networkidle' })
await page.waitForTimeout(1000)
// Клик на ряд FOOD MARKET — берём первую строку с этим текстом и в ней
// первую кнопку-ссылку (login-icon).
const rows = await page.$$('table tbody tr, tbody tr, [role="row"]')
let opened = false
for (const r of rows) {
  const txt = (await r.innerText()).trim()
  if (/FOOD MARKET/i.test(txt)) {
    const btn = await r.$('a, button')
    if (btn) {
      await btn.click()
      opened = true
      break
    }
  }
}
if (!opened) {
  // Fallback: клик по последней login-стрелке (там обычно FOOD MARKET).
  const arrows = await page.$$('a[href*="/api/super-admin/organizations/"][href*="open"], button[title*="ткрыт"]')
  if (arrows.length) await arrows[arrows.length - 1].click()
}
await page.waitForTimeout(2000)
await page.waitForLoadState('networkidle')
console.log('after override →', page.url())

const shots = [
  { name: 'dashboard-hero.png',  path: '/dashboard',                vp: { width: 1600, height: 1000 } },
  { name: 'analytics.png',       path: '/dashboard',                vp: { width: 1600, height: 1000 }, scrollY: 500 },
  { name: 'catalog.png',         path: '/catalog/products',         vp: { width: 1600, height: 1000 } },
  { name: 'product-card.png',    path: '/catalog/products',         vp: { width: 1200, height: 900  }, openFirst: true },
  { name: 'counterparties.png',  path: '/catalog/counterparties',   vp: { width: 1200, height: 900  } },
  { name: 'supply-form.png',     path: '/purchases/supplies/new',   vp: { width: 1200, height: 900  } },
]

// CSS, скрывающий override-warning баннер (оранжевую полосу сверху).
const HIDE_OVERRIDE_CSS = `
  [class*="bg-orange"], [class*="bg-amber"], [class*="bg-yellow-4"],
  [class*="ENV"], header [class*="orange"], div[class*="режиме"],
  div:has(> *:not(:empty):where(:scope:contains("СУПЕР-АДМИНА"))) { display: none !important; }
`

for (const s of shots) {
  console.log('shot', s.name, '←', s.path)
  await page.setViewportSize(s.vp)
  await page.goto(`${APP}${s.path}`, { waitUntil: 'networkidle' })
  await page.waitForTimeout(2000)
  // Убираем оранжевый override-баннер по тексту.
  await page.evaluate(() => {
    document.querySelectorAll('div, header').forEach((el) => {
      const t = el.textContent || ''
      if (/В РЕЖИМЕ СУПЕР-АДМИНА/i.test(t) && el.children.length < 6 && el.offsetHeight < 80) {
        el.style.display = 'none'
      }
    })
  })
  if (s.scrollY) {
    await page.evaluate((y) => window.scrollTo(0, y), s.scrollY)
    await page.waitForTimeout(500)
  }
  if (s.openFirst) {
    const cellLink = await page.$('table tbody tr td a, table tbody tr td button')
    if (cellLink) {
      try {
        await cellLink.click()
        await page.waitForLoadState('networkidle', { timeout: 10000 })
        await page.waitForTimeout(2000)
      } catch (e) {
        console.warn('  openFirst click failed:', e.message)
      }
    } else {
      // Fallback: клик в первую ячейку строки.
      const firstCell = await page.$('table tbody tr')
      if (firstCell) {
        try { await firstCell.click(); await page.waitForTimeout(2000) } catch {}
      }
    }
  }
  await page.screenshot({ path: path.join(OUT, s.name), fullPage: false })
  console.log('  ok →', s.name, s.vp.width + 'x' + s.vp.height)
}

await browser.close()
console.log('done')
