#include "mandelbrot.h"
#include <math.h>

// Clamp helper
static int clamp(int val) {
    if (val < 0) return 0;
    if (val > 255) return 255;
    return val;
}

// Mandelbrot iterations
int mandelbrot(Complex z0, int max_iter) {
    Complex z = z0;
    for (int i = 0; i < max_iter; i++) {
        if (complex_abs(z) > 2.0) return i;
        z = complex_add(complex_mul(z, z), z0);
    }
    return max_iter;
}

// Simple HSV -> RGB helper
static Color hsv_to_rgb(double h, double s, double v) {
    double r = 0, g = 0, b = 0;

    int i = (int)(h * 6);
    double f = h * 6 - i;
    double p = v * (1 - s);
    double q = v * (1 - f * s);
    double t = v * (1 - (1 - f) * s);

    switch (i % 6) {
    case 0: r = v; g = t; b = p; break;
    case 1: r = q; g = v; b = p; break;
    case 2: r = p; g = v; b = t; break;
    case 3: r = p; g = q; b = v; break;
    case 4: r = t; g = p; b = v; break;
    case 5: r = v; g = p; b = q; break;
    }

    Color c = { (unsigned char)clamp((int)(r * 255)),
                (unsigned char)clamp((int)(g * 255)),
                (unsigned char)clamp((int)(b * 255)) };
    return c;
}

// Color Mandelbrot
Color color_mandelbrot(Complex z0, int max_iter) {
    int iter = mandelbrot(z0, max_iter);

    if (iter == max_iter)
        return (Color) { 0, 0, 0 }; // black inside the set

    // Map iteration to color hue
    double t = (double)iter / max_iter;
    double hue = 0.95 + 10 * t; // arbitrary scaling for more variation
    hue = fmod(hue, 1.0);
    double sat = 0.6;  // saturation
    double val = 1.0;  // brightness

    return hsv_to_rgb(hue, sat, val);
}
