import type { TileExpression, TileRenderOptions, TileResult } from '../core/types'

export function renderTilesToCanvas(
  pattern: TileExpression,
  options: TileRenderOptions
): TileResult {
  const { width, height, tileSize, time, backgroundColor, foregroundColor } = options

  const canvas = document.createElement('canvas')
  canvas.width = width
  canvas.height = height

  const ctx = canvas.getContext('2d')!

  // Fill background
  ctx.fillStyle = backgroundColor
  ctx.fillRect(0, 0, width, height)

  // Set foreground color
  ctx.fillStyle = foregroundColor

  // Calculate grid dimensions
  const tilesX = Math.ceil(width / tileSize)
  const tilesY = Math.ceil(height / tileSize)

  // Render each tile
  for (let y = 0; y < tilesY; y++) {
    for (let x = 0; x < tilesX; x++) {
      const tileIndex = y * tilesX + x

      try {
        const result = pattern.compiled(x, y, tileIndex, time, Math.max(tilesX, tilesY))

        // Convert result to boolean
        const shouldFill = typeof result === 'boolean' ? result : result > 0.5

        if (shouldFill) {
          ctx.fillRect(
            x * tileSize,
            y * tileSize,
            tileSize,
            tileSize
          )
        }
      } catch (error) {
        // Skip tiles that cause errors
        console.warn(`Error rendering tile at (${x}, ${y}):`, error)
      }
    }
  }

  const imageData = ctx.getImageData(0, 0, width, height)

  return {
    canvas,
    imageData
  }
}

export function renderTilesToImageData(
  pattern: TileExpression,
  options: TileRenderOptions
): ImageData {
  const result = renderTilesToCanvas(pattern, options)
  return result.imageData
}