
#include "low_level_display_sfml.h"
#include <SFML/Window.hpp>
#include <SFML/Graphics.hpp>
#include <vector>

// Add missing method implementations for emulator linkage
std::optional<sf::Event> LowLevelDisplaySFML::pollEvent() {
    return window.pollEvent();
}

void LowLevelDisplaySFML::close() {
    window.close();
}

LowLevelDisplaySFML::LowLevelDisplaySFML(int w, int h)
    : width(w), height(h), 
      window(sf::VideoMode({(unsigned)w, (unsigned)h}), "basic1 Emulator"),
      framebuffer((w * h + 7) / 8, 0) {}

bool LowLevelDisplaySFML::init() {
    if (!texture.resize({(unsigned)width, (unsigned)height})) {
        return false;
    }
    sprite.emplace(texture);
    return window.isOpen();
}

void LowLevelDisplaySFML::draw_buffer(const uint8_t* bit_buffer) {
    // Convert 1-bit buffer to 8-bit grayscale (or RGBA) for SFML
    // Each bit in bit_buffer represents a pixel (0=black, 1=white)
    std::vector<std::uint8_t> pixels(width * height * 4, 0);
    for (int y = 0; y < height; ++y) {
        for (int x = 0; x < width; ++x) {
            int bit_index = y * width + x;
            int byte_index = bit_index / 8;
            int bit_offset = 7 - (bit_index % 8);
            bool on = (bit_buffer[byte_index] >> bit_offset) & 0x1;
            int idx = (y * width + x) * 4;
            std::uint8_t color = on ? 255 : 0;
            pixels[idx + 0] = color; // R
            pixels[idx + 1] = color; // G
            pixels[idx + 2] = color; // B
            pixels[idx + 3] = 255;   // A
        }
    }
    texture.update(pixels.data());
}

void LowLevelDisplaySFML::refresh() {
    window.clear(sf::Color::Black);
    if (sprite) {
        window.draw(*sprite);
    }
    window.display();
}

bool LowLevelDisplaySFML::isOpen() const {
    return window.isOpen();
}
