let selectedItem = "";
let animationFrame = 0;
let impactFrame = 0;
let shakeAmount = 0;
let angle = 0;
let img;
let sound;
let currentMode = 'manual';
let soundPlayed = false; // Flag to check if sound has been played

function preload() {
  // This can be used for loading assets, but we're doing it in the randomize() function instead
}

function setup() {
  let canvas = createCanvas(400, 200);
  canvas.parent('canvasContainer');
  angleMode(DEGREES);
  textAlign(CENTER, CENTER);
  textSize(24);
  setMode(currentMode); // Initialize input section when the page loads
}

function draw() {
  background(255);

  if (animationFrame > 0 && img) {
    // Spin animation
    push();
    translate(width / 2, height / 2);
    rotate(angle);
    image(img, -25, -25, 50, 50); // Image is centered at (width / 2, height / 2)
    pop();
    angle += 0.2; // Spin speed
    animationFrame--;
  } else if (impactFrame < 30 && img) { // Increased shake duration
    shakeAmount = 5; // Reduced shake intensity
    let shakeX = random(-shakeAmount, shakeAmount);
    let shakeY = random(-shakeAmount, shakeAmount);
    image(img, width / 2 - 25 + shakeX, height / 2 - 25 + shakeY, 50, 50); // Shake effect

    // Play sound only once
    if (impactFrame === 1 && !soundPlayed && sound) {
      sound.play();
      soundPlayed = true; // Set flag to prevent repeated sound
    }
    impactFrame++;
  } else if (impactFrame >= 30 && img) {
    // After spinning and shaking, display the "Eat this" message
    document.getElementById('result').innerText = `Eat this: ${selectedItem}!`;

    // Shake the text a bit before resetting the animation
    let shakeTextAmount = 5;
    let shakeX = random(-shakeTextAmount, shakeTextAmount);
    let shakeY = random(-shakeTextAmount, shakeTextAmount);

    // Position the text with shake effect
    document.getElementById('result').style.transform = `translate(${shakeX}px, ${shakeY}px)`;

    // Auto-reset after 2 seconds
    if (frameCount % 120 === 0) {
      resetAnimation();
    }
  }
}

function setMode(mode) {
  currentMode = mode;
  let inputSection = document.getElementById('inputSection');
  if (mode === 'manual') {
    inputSection.innerHTML = `
      <p>Enter menu items (one per line):</p>
      <textarea id="menuInput" rows="5" placeholder="Pizza\nBurger\nSalad"></textarea>
    `;
  } else {
    inputSection.innerHTML = `
      <p>Upload a menu image:</p>
      <input type="file" id="imageInput" accept="image/*" onchange="scanImage()">
      <p>Extracted items:</p>
      <textarea id="menuInput" rows="5" placeholder="Items will appear here"></textarea>
    `;
  }
}

async function scanImage() {
  if (currentMode !== 'image') return;
  const fileInput = document.getElementById('imageInput');
  const resultDiv = document.getElementById('result');

  if (!fileInput.files[0]) return;

  resultDiv.innerText = "Scanning image...";
  try {
    const { data: { text } } = await Tesseract.recognize(fileInput.files[0], 'eng');
    const items = text.split('\n').filter(item => item.trim() && !/^\d+\.?\s*$/.test(item));
    document.getElementById('menuInput').value = items.join('\n');
    resultDiv.innerText = items.length > 0 ? "Items extracted! Click Randomize." : "No items found.";
  } catch (err) {
    resultDiv.innerText = "Error scanning image: " + err.message;
    console.error(err);
  }
}

function randomize() {
  if (animationFrame > 0 || impactFrame > 0) return; // Prevent starting another animation if one is already running

  const menuInput = document.getElementById('menuInput');
  const items = menuInput.value.trim().split('\n').filter(item => item.trim());

  if (items.length === 0) {
    document.getElementById('result').innerText = "Please enter or scan items.";
    return;
  }

  selectedItem = random(items); // Select a random item from the list
  animationFrame = 180; // 3 seconds spin animation
  impactFrame = 0;
  angle = 0;
  document.getElementById('result').innerText = "Randomizing...";

  // Load image and sound when randomize is pressed
  img = loadImage('Images/food_spin.jpg', () => {
    console.log('Image loaded successfully');
  }, (e) => console.error('Image load error:', e));

  sound = loadSound('Sounds/superidol.mp3', () => {
    console.log('Sound loaded successfully');
  }, (e) => console.error('Sound load error:', e));

  soundPlayed = false; // Reset soundPlayed flag for next round
}

function resetAnimation() {
  animationFrame = 0;
  impactFrame = 0;
  soundPlayed = false;
  document.getElementById('result').style.transform = 'translate(0, 0)'; // Reset text shake position
}


the code, after presing randomise, it just hsakes ,does not spin (eaT this) and th esound plays on loop like its eben pressed play each 0.02 s