#pragma once

// IWYU pragma: private

#include "platforms/esp/32/feature_flags/enabled.h"

#if FASTLED_ESP32_HAS_CLOCKLESS_SPI

// signal to the world that we have a ClocklessController to allow WS2812 and others.
#define FL_CLOCKLESS_CONTROLLER_DEFINED 1
// Mark that new ChannelEngine-based ClocklessSPI is defined (prevents old alias collision)
#define FL_CLOCKLESS_SPI_CHANNEL_ENGINE_DEFINED 1

#include "crgb.h"
#include "eorder.h"
#include "pixel_iterator.h"
#include "fl/channels/bus.h"
#include "fl/channels/data.h"
#include "fl/channels/driver.h"
#include "fl/channels/manager.h"
#include "fl/chipsets/timing_traits.h"
#include "fl/log/log.h"
#include "fl/stl/noexcept.h"
#include "fl/stl/static_assert.h"
#include "platforms/esp/32/drivers/spi/bus_traits.h"

namespace fl {
template <int DATA_PIN, typename TIMING, EOrder RGB_ORDER = RGB, int XTRA0 = 0, bool FLIP = false, int WAIT_TIME = 5>
class ClocklessSPI : public CPixelLEDController<RGB_ORDER>
{
private:
    // Channel data for transmission
    ChannelDataPtr mChannelData;

    // Channel driver reference (selected dynamically from bus manager)
    fl::shared_ptr<IChannelDriver> mDriver;

    // -- Verify that the pin is valid
    FL_STATIC_ASSERT(FastPin<DATA_PIN>::validpin(), "This pin has been marked as an invalid pin, common reasons includes it being a ground pin, read only, or too noisy (e.g. hooked up to the uart).");

public:
    ClocklessSPI()
        : mDriver(getClocklessSpiEngine())
    {
        // Create channel data with pin and timing configuration
        ChipsetTimingConfig timing = makeTimingConfig<TIMING>();
        mChannelData = ChannelData::create(DATA_PIN, timing);
    }

    void init() FL_NOEXCEPT override { }
    virtual u16 getMaxRefreshRate() const FL_NOEXCEPT { return 800; }

protected:
    // -- Show pixels
    //    This is the main entry point for the controller.
    virtual void showPixels(PixelController<RGB_ORDER> &pixels) FL_NOEXCEPT override
    {
        if (!mDriver) {
            FL_WARN_EVERY(100, "No Engine");
            return;
        }
        // Wait for previous transmission to complete and release buffer
        // This prevents race conditions when show() is called faster than hardware can transmit
        u32 startTime = fl::millis();
        u32 lastWarnTime = startTime;
        if (mChannelData->isInUse()) {
            FL_WARN_EVERY(100, "ClocklessSPI: driver should have finished transmitting by now - waiting");
            bool finished = mDriver->waitForReady();
            if (!finished) {
                FL_ERROR("ClocklessSPI: Engine still busy after " << fl::millis() - startTime << "ms");
                return;
            }
        }

        // Convert pixels to encoded byte data
        fl::PixelIterator iterator = pixels.as_iterator(this->getRgbw());
        auto& data = mChannelData->getData();
        data.clear();
        iterator.writeWS2812(&data);

        // Enqueue for transmission (will be sent when driver->show() is called)
        mDriver->enqueue(mChannelData);
    }

    static fl::shared_ptr<IChannelDriver> getClocklessSpiEngine() FL_NOEXCEPT {
        // Phase 5c of #2428: bypass `ChannelManager` and bind directly to
        // the `BusTraits<Bus::SPI>` singleton. Naming
        // `BusTraits<Bus::SPI>::instancePtr()` here is the ODR-use that
        // lets the linker keep ONLY the SPI clockless driver TU -- post-#2428
        // the ChannelManager-driven registry path is gone.
        return BusTraits<Bus::SPI>::instancePtr();
    }
};
}  // namespace fl

#endif // FASTLED_ESP32_HAS_CLOCKLESS_SPI
