import type { ClientPuzzle, CellStatus } from './types'

const GREEN = '\u{1F7E9}'
const YELLOW = '\u{1F7E8}'
const RED = '\u{1F7E5}'
const BLACK = '\u{2B1B}'
const WHITE = '\u{2B1C}'

function formatTime(secs: number): string {
  const m = Math.floor(secs / 60)
  const s = secs % 60
  return `${m}:${s.toString().padStart(2, '0')}`
}

export function generateShareText(
  puzzle: ClientPuzzle,
  entries: string[][],
  cellStatus: CellStatus[][],
  elapsed: number,
  hintsUsed: number,
  shortId: string | null,
  preset: string | null,
  dailyDate?: string | null,
  cellEverWrong?: boolean[][],
): string {
  const date = dailyDate || new Date().toISOString().split('T')[0]
  const name = preset ? preset.charAt(0).toUpperCase() + preset.slice(1) : 'Custom'
  const lines: string[] = []

  lines.push(`cruciverb - ${name} - ${date}`)
  lines.push(`${puzzle.width}x${puzzle.height} - Time: ${formatTime(elapsed)} - Hints: ${hintsUsed}`)
  lines.push('')

  // only show emoji grid for small puzzles (up to 9x9)
  if (puzzle.width <= 9 && puzzle.height <= 9) {
    for (let r = 0; r < puzzle.height; r++) {
      let row = ''
      for (let c = 0; c < puzzle.width; c++) {
        if (puzzle.cells[r][c] === 'black') {
          row += BLACK
        } else if (!entries[r]?.[c]) {
          row += WHITE
        } else if (cellStatus[r]?.[c] === 'revealed') {
          row += YELLOW
        } else if (cellEverWrong?.[r]?.[c]) {
          row += RED
        } else {
          row += GREEN
        }
      }
      lines.push(row)
    }
  } else {
    // for larger grids, show a summary instead
    let clean = 0, hinted = 0, wrong = 0, blacks = 0
    for (let r = 0; r < puzzle.height; r++) {
      for (let c = 0; c < puzzle.width; c++) {
        if (puzzle.cells[r][c] === 'black') { blacks++ }
        else if (cellStatus[r]?.[c] === 'revealed') { hinted++ }
        else if (cellEverWrong?.[r]?.[c]) { wrong++ }
        else { clean++ }
      }
    }
    const cells = puzzle.width * puzzle.height - blacks
    lines.push(`${GREEN} ${clean}/${cells} cells clean`)
    if (wrong > 0) lines.push(`${RED} ${wrong} needed correction`)
    if (hinted > 0) lines.push(`${YELLOW} ${hinted} hints used`)
  }

  lines.push('')
  if (dailyDate && preset) {
    lines.push(`${window.location.origin}/daily/${preset}`)
  } else if (shortId) {
    lines.push(`${window.location.origin}/p/${shortId}`)
  }

  return lines.join('\n')
}
