#include "raylib.h"
#include "raymath.h"
#include "Spider.hpp"
#include "World.hpp"
#include <cmath>

int main() {
  const int screenWidth = 1200;
  const int screenHeight = 800;
  InitWindow(screenWidth, screenHeight, "Arachne");
  SetTargetFPS(60);

  Spider arachne({(float)screenWidth / 2, (float)screenHeight / 2});

  World world(15, screenWidth, screenHeight);

  while (!WindowShouldClose()) {
    world.update();
    world.respawn(15);

    for (auto& fly : world.flies) {
      if (!fly.isAlive) continue;

      Vector2 toFly = Vector2Subtract(fly.position, arachne.position);
      float dist = Vector2Length(toFly);

      if (dist < 20.0f) {
        fly.isAlive = false;
        continue;
      }

      for (const auto& eye : arachne.eyes) {
        if (dist < eye.range) {
          float absEyeAng = arachne.angle + eye.angleOffset * DEG2RAD;
          Vector2 viewDir = {cosf(absEyeAng), sinf(absEyeAng)};
          Vector2 toFlyNorm = Vector2Normalize(toFly);

          float dot = Vector2DotProduct(toFlyNorm, viewDir);
          float angleToFly = acosf(fmaxf(-1.0f, fminf(1.0f, dot))) * RAD2DEG;

          if (angleToFly < eye.fov / 2.0f) {
            float intensity = (1.0f - dist / eye.range) * 0.5f;
            arachne.brain.stimulate(eye.unitIdx, intensity);
          }
        }
      }
    }

    for (const auto& fly : world.flies) {
      if (!fly.isAlive) continue;

      for (int i = 0; i < 8; i++) {
        float legOff = (i < 4) ? (-135.0f + i * 30.0f) : (45.0f + (i - 4) * 30.0f);
        Vector2 legPos = Vector2Add(arachne.position, Vector2Rotate({40, 0}, arachne.angle + legOff * DEG2RAD));
        float distToLeg = Vector2Distance(fly.position, legPos);

        if (distToLeg < 150.0f) {
          float vibPower = 0.3f * (1.0f - distToLeg / 150.0f);
          arachne.brain.stimulate(arachne.vibrationUnits[i], vibPower);
        }
      }
    }

    arachne.update();

    BeginDrawing();
    ClearBackground((Color){30, 30, 40, 255});

    arachne.draw();

    DrawText("NEURAL NETWORK ACTIVITY", 950, 20, 10, GRAY);
    arachne.brain.draw({1000, 50}, 8, 30.0f);
    world.draw();

    DrawFPS(10, 10);
    EndDrawing();
  }

  CloseWindow();
  return 0;
}