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

// Add missing method implementations for emulator linkage
bool LowLevelDisplaySFML::pollEvent(sf::Event& event) {
    return window.pollEvent(event);
}

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

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

bool LowLevelDisplaySFML::init() {
    texture.create(width, height);
    sprite.setTexture(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<sf::Uint8> 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;
            sf::Uint8 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() {
    sf::Event event;
    while (window.pollEvent(event)) {
        if (event.type == sf::Event::Closed)
            window.close();
        // TODO: Handle mouse/keyboard input here
    }
    window.clear(sf::Color::Black);
    window.draw(sprite);
    window.display();
}

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