#pragma once
#include <Arduino.h>
#include <Arduino_BMI270_BMM150.h>
#include "filters.h"

/*
 ===========================================================
    MODULE PhiMagnetometer
    Détection champ magnétique terrestre + perturbations
 ===========================================================
*/

class PhiMagnetometer {
public:
    PhiMagnetometer();

    // Initialisation (IMU.begin() doit être appelé avant)
    bool begin();

    // Calibration baseline (appeler au setup, environnement stable)
    void calibrateBaseline(uint16_t samples = 200);

    // Mise à jour (appeler à ~50 Hz)
    void update();

    // Métriques scientifiques
    float magnitude() const { return _magnitude; }
    float delta() const { return _deltaMag; }
    float baseline() const { return _baseline; }

    // Composantes vectorielles (pour orientation)
    void getComponents(float &x, float &y, float &z) const {
        x = _x; y = _y; z = _z;
    }

    // Direction 2D (pour boussole visuelle)
    float getAngle() const {
        return atan2f(_y, _x);
    }

private:
    float _x, _y, _z;           // Composantes µT
    float _magnitude;           // ||B|| total
    float _deltaMag;            // Écart au baseline
    float _baseline;            // Champ terrestre local
    bool  _calibrated;

    LowPass _lpf;               // Lissage (α=0.1)
};
