// Self-contained collectors for page.evaluate() — NO external module refs
// (they are serialized into the browser context). collectVisibleText is moved
// verbatim from tests/render-verification-react/named-slot-projection.spec.ts.

export const collectVisibleText = (): string => {
  const out: string[] = []
  const walk = (root: Document | ShadowRoot) => {
    for (const el of Array.from(root.querySelectorAll('*'))) {
      if ((el as Element & { shadowRoot?: ShadowRoot | null }).shadowRoot) {
        walk((el as Element & { shadowRoot: ShadowRoot }).shadowRoot)
      }
      for (const n of Array.from(el.childNodes)) {
        if (n.nodeType === 3 && (n.textContent ?? '').trim()) {
          const vis = typeof (el as unknown as { checkVisibility?: (o: object) => boolean }).checkVisibility === 'function'
            ? (el as unknown as { checkVisibility: (o: object) => boolean }).checkVisibility({ checkOpacity: true, checkVisibilityCSS: true })
            : true
          if (vis) out.push((n.textContent ?? '').trim())
        }
      }
    }
  }
  walk(document)
  return out.join(' | ')
}

export const collectElementOutline = (): Record<string, number> => {
  const counts: Record<string, number> = { nav: 0, a: 0, button: 0, input: 0, img: 0, svg: 0, customElement: 0 }
  const walk = (root: Document | ShadowRoot) => {
    for (const el of Array.from(root.querySelectorAll('*'))) {
      const tag = el.tagName.toLowerCase()
      if (tag in counts) counts[tag]++
      if (tag.includes('-')) counts.customElement++
      if ((el as Element & { shadowRoot?: ShadowRoot | null }).shadowRoot) {
        walk((el as Element & { shadowRoot: ShadowRoot }).shadowRoot)
      }
    }
  }
  walk(document)
  return counts
}
