import { Card } from '../../types';

export const getMostCommon = (arr: any[]) => {
  if (arr.length === 0) return null;
  const counts: Record<string, number> = {};
  arr.forEach(item => counts[item] = (counts[item] || 0) + 1);
  return Object.entries(counts).sort((a, b) => b[1] - a[1])[0][0];
};

export const createCrop = (ctx: CanvasRenderingContext2D, canvas: HTMLCanvasElement, region: {x: number, y: number, width: number, height: number}): HTMLCanvasElement => {
  const cropCanvas = document.createElement('canvas');
  cropCanvas.width = region.width;
  cropCanvas.height = region.height;
  const cropCtx = cropCanvas.getContext('2d');
  if (cropCtx) {
    cropCtx.drawImage(canvas, region.x, region.y, region.width, region.height, 0, 0, region.width, region.height);
  }
  return cropCanvas;
};

export const detectCardSuit = (ctx: CanvasRenderingContext2D, canvas: HTMLCanvasElement, region: {x: number, y: number, width: number, height: number}): 'Schellen' | 'Schilten' | 'Eicheln' | 'Rosen' => {
  const regionCanvas = document.createElement('canvas');
  const regionCtx = regionCanvas.getContext('2d');
  
  if (!regionCtx) return 'Schellen';
  
  const padding = 5;
  regionCanvas.width = region.width + padding * 2;
  regionCanvas.height = region.height + padding * 2;
  
  regionCtx.drawImage(
    canvas,
    region.x - padding, region.y - padding, region.width + padding * 2, region.height + padding * 2,
    0, 0, regionCanvas.width, regionCanvas.height
  );
  
  const regionData = regionCtx.getImageData(0, 0, regionCanvas.width, regionCanvas.height);
  const data = regionData.data;
  
  let redPixels = 0;
  let greenPixels = 0;
  let blackPixels = 0;
  let yellowPixels = 0;
  let whitePixels = 0;
  let otherPixels = 0;
  
  const centerX = Math.floor(regionCanvas.width / 2);
  const centerY = Math.floor(regionCanvas.height / 2);
  
  const sampleSize = 8;
  for (let dy = -sampleSize; dy < sampleSize; dy += 2) {
    for (let dx = -sampleSize; dx < sampleSize; dx += 2) {
      const px = Math.max(0, Math.min(regionCanvas.width - 1, centerX + dx));
      const py = Math.max(0, Math.min(regionCanvas.height - 1, centerY + dy));
      
      const i = (py * regionCanvas.width + px) * 4;
      const r = data[i];
      const g = data[i + 1];
      const b = data[i + 2];
      
      const brightness = (r + g + b) / 3;
      const saturation = Math.max(r, g, b) - Math.min(r, g, b);
      
      if (brightness > 240 && saturation < 20) {
        whitePixels++;
      } else if (r > 200 && g < 100 && b < 100) {
        redPixels++;
      } else if (g > 200 && r < 100 && b < 100) {
        greenPixels++;
      } else if (r < 100 && g < 100 && b < 100) {
        blackPixels++;
      } else if (r > 200 && g > 200 && b < 100) {
        yellowPixels++;
      } else {
        otherPixels++;
      }
    }
  }
  
  const colors = { redPixels, greenPixels, blackPixels, yellowPixels, whitePixels };
  const maxCount = Math.max(...Object.values(colors));
  
  if (maxCount < 5) {
    return 'Schellen';
  }
  
  if (colors.redPixels === maxCount) return 'Rosen';
  if (colors.greenPixels === maxCount) return 'Schilten';
  if (colors.blackPixels === maxCount) return 'Eicheln';
  if (colors.yellowPixels === maxCount) return 'Schellen';
  
  const sortedColors = Object.entries(colors)
    .sort((a, b) => b[1] - a[1])
    .map(entry => entry[0]);
  
  if (sortedColors.length >= 2 && sortedColors[0] !== 'whitePixels') {
    if (sortedColors[0] === 'redPixels') return 'Rosen';
    if (sortedColors[0] === 'greenPixels') return 'Schilten';
    if (sortedColors[0] === 'blackPixels') return 'Eicheln';
    if (sortedColors[0] === 'yellowPixels') return 'Schellen';
  }
  
  return 'Schellen';
};

export const detectCardValue = (ctx: CanvasRenderingContext2D, canvas: HTMLCanvasElement, region: {x: number, y: number, width: number, height: number}): number => {
  const values = [6, 7, 8, 9, 10, 11, 12, 13];
  const randomIndex = Math.floor(Math.random() * values.length);
  return values[randomIndex];
};

export const getCardRegionWithShapeAnalysis = (imageData: ImageData, width: number, height: number, x: number, y: number): {x: number, y: number, width: number, height: number} | null => {
  let minX = x, maxX = x;
  let minY = y, maxY = y;
  let pixelCount = 0;
  
  const stack = [[x, y]];
  const visited = new Int32Array(width * height).fill(-1);
  const searchLimit = 10000; 
  
  let visitedCount = 0;
  while (stack.length > 0 && visitedCount < searchLimit) {
    const [cx, cy] = stack.pop()!;
    const idx = cy * width + cx;
    if (visited[idx] !== -1) continue;
    visited[idx] = 1;
    visitedCount++;
    
    if (cx >= 0 && cx < width && cy >= 0 && cy < height) {
      const i = idx * 4;
      const brightness = (imageData.data[i] + imageData.data[i + 1] + imageData.data[i + 2]) / 3;
      
      if (brightness > 120 && brightness < 250) {
        pixelCount++;
        minX = Math.min(minX, cx);
        maxX = Math.max(maxX, cx);
        minY = Math.min(minY, cy);
        maxY = Math.max(maxY, cy);
        
        if (cx + 1 < width) stack.push([cx + 1, cy]);
        if (cx - 1 >= 0) stack.push([cx - 1, cy]);
        if (cy + 1 < height) stack.push([cy + 1, cy]);
        if (cy - 1 >= 0) stack.push([cy, cy - 1]);
      }
    }
  }
  
  const widthDiff = maxX - minX;
  const heightDiff = maxY - minY;
  
  if (pixelCount > 200 && widthDiff > 50 && heightDiff > 80) {
    return {
      x: minX,
      y: minY,
      width: widthDiff,
      height: heightDiff
    };
  }
  
  return null;
};
