import { GEOMETRIC_PATTERNS, renderTilesToCanvas } from '../geometric-tiles'
import type { GeneratedImage } from '../stores'

const patternNames = Object.keys(GEOMETRIC_PATTERNS)

const colorPalettes = [
  { bg: '#000000', fg: '#ffffff' },
  { bg: '#ffffff', fg: '#000000' },
  { bg: '#000000', fg: '#cccccc' },
  { bg: '#000000', fg: '#888888' },
  { bg: '#1a1a1a', fg: '#ffffff' },
  { bg: '#333333', fg: '#ffffff' },
  { bg: '#000000', fg: '#666666' },
  { bg: '#222222', fg: '#dddddd' }
]

const tileSizes = [2, 3, 4, 5, 6, 8, 10, 12, 16, 20, 24, 32]

export function generateGeometricTilesImages(count: number, size: number): GeneratedImage[] {
  const images: GeneratedImage[] = []

  for (let i = 0; i < count; i++) {
    const patternName = patternNames[Math.floor(Math.random() * patternNames.length)]
    const pattern = GEOMETRIC_PATTERNS[patternName]
    const palette = colorPalettes[Math.floor(Math.random() * colorPalettes.length)]

    // More varied tile size selection
    let tileSize: number
    const sizeVariation = Math.random()
    if (sizeVariation < 0.3) {
      // Small tiles (high detail)
      tileSize = tileSizes[Math.floor(Math.random() * 4)] // 2-5
    } else if (sizeVariation < 0.7) {
      // Medium tiles
      tileSize = tileSizes[4 + Math.floor(Math.random() * 4)] // 6-12
    } else {
      // Large tiles (bold patterns)
      tileSize = tileSizes[8 + Math.floor(Math.random() * 4)] // 16-32
    }

    // Add some randomness to prevent identical patterns
    const timeOffset = Math.random() * 100

    try {
      const result = renderTilesToCanvas(pattern, {
        width: size,
        height: size,
        tileSize,
        time: timeOffset,
        backgroundColor: palette.bg,
        foregroundColor: palette.fg
      })

      const image = {
        id: `geotiles-${Date.now()}-${i}-${Math.floor(Math.random() * 1000)}`,
        canvas: result.canvas,
        imageData: result.imageData,
        generator: 'geometric-tiles',
        params: {
          pattern: patternName,
          tileSize,
          colors: palette,
          timeOffset
        }
      }

      images.push(image)
    } catch (error) {
      console.error(`Failed to generate geometric tiles image ${i + 1}:`, error)
    }
  }

  return images
}