// Patrick.tsx
import React, { useRef, useEffect } from 'react';
import './Patrick.css';

const Patrick: React.FC = () => {
  const canvasRef = useRef<HTMLCanvasElement | null>(null);
  const contextRef = useRef<CanvasRenderingContext2D | null>(null);
  var isPressed = false;

  useEffect(() => {
    const canvas = canvasRef.current;
    if (canvas) {
      canvas.width = 1000; // Set canvas width
      canvas.height = 500; // Set canvas height
      const context = canvas.getContext('2d');
      if (context) {
        contextRef.current = context;
        // Fill the canvas with a color
        context.fillStyle = 'black';
        context.fillRect(0, 0, canvas.width, canvas.height);
      }
    }
  }, []);

  const manipulatePixel = (x: number, y: number) => {
    const context = contextRef.current;
    if (context) {
      // Get the pixel data
      const imageData = context.getImageData(x, y, 1, 1);
      const data = imageData.data;

      // Manipulate the pixel (invert color)
      data[0] = 255; // Red
      data[1] = 255; // Green
      data[2] = 255; // Blue
      context.putImageData(imageData, x, y);
      context.putImageData(imageData, x+1, y);
      context.putImageData(imageData, x-1, y);
      context.putImageData(imageData, x, y+1);
      context.putImageData(imageData, x, y-1);
    }
  };

  const handleClick = (event: React.MouseEvent<HTMLCanvasElement>) => {
    const canvas = canvasRef.current;
    if (canvas && isPressed) {
      const rect = canvas.getBoundingClientRect();
      const x = Math.floor(event.clientX - rect.left);
      const y = Math.floor(event.clientY - rect.top);
      manipulatePixel(x, y);
    } else {
      isPressed = false;
    }
  };

  const moveDown = (event: React.MouseEvent<HTMLCanvasElement>) => {
    isPressed = true;
    handleClick(event)
  };

  const moveUp = () => {
    isPressed = false;
  };

  return (
    <div className="programmer-space patrick">
      <h1>Welcome to Patrick-Paint™.</h1>
      <br></br>
      <canvas
        ref={canvasRef}
        onMouseDown={moveDown}
        onMouseUp={moveUp}
        onMouseMove={handleClick}
        style={{ border: '1px solid black' }}
      />
    </div>
  );
};

export default Patrick;
