#include <jni.h>
#include <android/bitmap.h>
#include <android/log.h>

#include <vector>

#include "ThorRenderer.hpp"
#include "android/ThorGlRenderer.hpp"

#define LOG_TAG "ThorJni"

// Marshalls the parallel primitive arrays from Kotlin into ThorShapeDesc.
// params layout per shape (stride 8): [strokeWidth, g1..g6, closed].
//   rect: g1..g6 = x,y,w,h,rx,ry | circle: g1..g3 = cx,cy,radius | line: g1..g4 = x1,y1,x2,y2
// Polygons read pointCounts[i] floats from pointsFlat (concatenated).
static void buildScene(
    JNIEnv* env, jintArray types, jintArray fills, jintArray strokes,
    jfloatArray params, jfloatArray pointsFlat, jintArray pointCounts,
    std::vector<thor::ThorShapeDesc>& scene) {
  const jsize n = env->GetArrayLength(types);
  jint* typesA = env->GetIntArrayElements(types, nullptr);
  jint* fillsA = env->GetIntArrayElements(fills, nullptr);
  jint* strokesA = env->GetIntArrayElements(strokes, nullptr);
  jfloat* paramsA = env->GetFloatArrayElements(params, nullptr);
  jfloat* pointsA = env->GetFloatArrayElements(pointsFlat, nullptr);
  jint* countsA = env->GetIntArrayElements(pointCounts, nullptr);

  scene.clear();
  scene.reserve(static_cast<size_t>(n));
  int pointsOffset = 0;
  for (jsize i = 0; i < n; ++i) {
    thor::ThorShapeDesc d;
    d.type = static_cast<thor::ThorShapeType>(typesA[i]);

    const uint32_t fill = static_cast<uint32_t>(fillsA[i]);
    if ((fill >> 24) != 0u) {
      d.hasFill = true;
      d.fillColor = fill;
    }
    const uint32_t stroke = static_cast<uint32_t>(strokesA[i]);
    const jfloat* p = &paramsA[i * 8];
    const float sw = p[0];
    if ((stroke >> 24) != 0u && sw > 0.0f) {
      d.hasStroke = true;
      d.strokeColor = stroke;
      d.strokeWidth = sw;
    }
    d.closed = (p[7] != 0.0f);

    switch (d.type) {
      case thor::ThorShapeType::Rect:
        d.x = p[1]; d.y = p[2]; d.w = p[3]; d.h = p[4]; d.rx = p[5]; d.ry = p[6];
        break;
      case thor::ThorShapeType::Circle:
        d.cx = p[1]; d.cy = p[2]; d.radius = p[3];
        break;
      case thor::ThorShapeType::Line:
        d.x1 = p[1]; d.y1 = p[2]; d.x2 = p[3]; d.y2 = p[4];
        break;
      case thor::ThorShapeType::Polygon: {
        const int count = countsA[i];
        d.points.assign(pointsA + pointsOffset, pointsA + pointsOffset + count);
        break;
      }
    }
    pointsOffset += countsA[i];
    scene.push_back(std::move(d));
  }

  env->ReleaseIntArrayElements(types, typesA, JNI_ABORT);
  env->ReleaseIntArrayElements(fills, fillsA, JNI_ABORT);
  env->ReleaseIntArrayElements(strokes, strokesA, JNI_ABORT);
  env->ReleaseFloatArrayElements(params, paramsA, JNI_ABORT);
  env->ReleaseFloatArrayElements(pointsFlat, pointsA, JNI_ABORT);
  env->ReleaseIntArrayElements(pointCounts, countsA, JNI_ABORT);
}

extern "C" {

// ---- CPU path: one ThorRenderer per view (created/destroyed by ThorCanvasView) ----
// Per-view (not a shared static) so two canvases never race on one renderer/canvas
// and never thrash its SwCanvas target back and forth between their bitmaps.
JNIEXPORT jlong JNICALL
Java_com_margelo_nitro_thor_ThorNative_nativeCpuCreate(JNIEnv*, jobject) {
  return reinterpret_cast<jlong>(new thor::ThorRenderer());
}

JNIEXPORT void JNICALL
Java_com_margelo_nitro_thor_ThorNative_nativeCpuDestroy(JNIEnv*, jobject, jlong ptr) {
  if (ptr != 0) delete reinterpret_cast<thor::ThorRenderer*>(ptr);
}

// Rasterize into an Android Bitmap (RGBA). Kotlin's renderLock serializes calls
// for a given view, so the thread_local scratch scene is race-free even when the
// worklet fast-path and the UI thread drive the same view on different threads.
JNIEXPORT void JNICALL
Java_com_margelo_nitro_thor_ThorNative_nativeRenderScene(
    JNIEnv* env, jobject, jlong ptr, jobject bitmap, jint width, jint height,
    jintArray types, jintArray fills, jintArray strokes, jfloatArray params,
    jfloatArray pointsFlat, jintArray pointCounts) {
  if (ptr == 0 || bitmap == nullptr || width <= 0 || height <= 0) return;
  static thread_local std::vector<thor::ThorShapeDesc> scene; // reused across frames
  buildScene(env, types, fills, strokes, params, pointsFlat, pointCounts, scene);

  void* pixels = nullptr;
  if (AndroidBitmap_lockPixels(env, bitmap, &pixels) != ANDROID_BITMAP_RESULT_SUCCESS) {
    __android_log_print(ANDROID_LOG_ERROR, LOG_TAG, "lockPixels failed");
    return;
  }
  reinterpret_cast<thor::ThorRenderer*>(ptr)->renderScene(
      reinterpret_cast<uint32_t*>(pixels), static_cast<uint32_t>(width),
      static_cast<uint32_t>(height), scene, thor::PixelFormat::RGBA);
  AndroidBitmap_unlockPixels(env, bitmap);
}

// ---- GPU path: ThorVG GL engine into the current EGL surface ----
JNIEXPORT jlong JNICALL
Java_com_margelo_nitro_thor_ThorNative_nativeGlCreate(JNIEnv*, jobject) {
  return reinterpret_cast<jlong>(new thor::ThorGlRenderer());
}

JNIEXPORT void JNICALL
Java_com_margelo_nitro_thor_ThorNative_nativeGlResize(
    JNIEnv*, jobject, jlong ptr, jint width, jint height) {
  if (ptr == 0) return;
  reinterpret_cast<thor::ThorGlRenderer*>(ptr)->resize(
      static_cast<uint32_t>(width), static_cast<uint32_t>(height));
}

JNIEXPORT void JNICALL
Java_com_margelo_nitro_thor_ThorNative_nativeGlRender(
    JNIEnv* env, jobject, jlong ptr, jintArray types, jintArray fills,
    jintArray strokes, jfloatArray params, jfloatArray pointsFlat, jintArray pointCounts) {
  if (ptr == 0) return;
  static thread_local std::vector<thor::ThorShapeDesc> scene; // reused across frames (GL thread)
  buildScene(env, types, fills, strokes, params, pointsFlat, pointCounts, scene);
  reinterpret_cast<thor::ThorGlRenderer*>(ptr)->renderScene(scene);
}

JNIEXPORT void JNICALL
Java_com_margelo_nitro_thor_ThorNative_nativeGlDestroy(JNIEnv*, jobject, jlong ptr) {
  if (ptr != 0) delete reinterpret_cast<thor::ThorGlRenderer*>(ptr);
}

} // extern "C"
