/*
Crafter®.Graphics
Copyright (C) 2026 Catcrafts®
catcrafts.net

This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License version 3.0 as published by the Free Software Foundation;

This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.

You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301 USA
*/

// Router implementation. The popState handler table lives in
// Crafter.Graphics-Dom.cpp (alongside every other event-kind table);
// we reach it through the opaque `PopStateRegister`/`PopStateUnregister`
// helpers it exposes, avoiding any cross-TU duplication of the
// HandlerTable definition.

module;
module Crafter.Graphics;
import std;

namespace Crafter::DomBindings {
    __attribute__((import_module("env"), import_name("pushState")))
    void PushState(const char* data, std::int32_t dataLength,
                   const char* title, std::int32_t titleLength,
                   const char* url, std::int32_t urlLength);
    __attribute__((import_module("env"), import_name("addPopStateListener")))
    void AddPopStateListener(std::int32_t id);
    __attribute__((import_module("env"), import_name("removePopStateListener")))
    void RemovePopStateListener(std::int32_t id);
    __attribute__((import_module("env"), import_name("getPathName")))
    const char* GetPathName();

    // Defined in Crafter.Graphics-Dom.cpp.
    std::int32_t PopStateRegister(std::function<void()> cb);
    void         PopStateUnregister(std::int32_t id);
}

namespace Crafter::Router {

    void PushState(std::string_view data, std::string_view title, std::string_view url) {
        Crafter::DomBindings::PushState(
            data.data(),  static_cast<std::int32_t>(data.size()),
            title.data(), static_cast<std::int32_t>(title.size()),
            url.data(),   static_cast<std::int32_t>(url.size()));
    }

    std::int32_t AddPopStateListener(std::function<void()> callback) {
        std::int32_t id = Crafter::DomBindings::PopStateRegister(std::move(callback));
        Crafter::DomBindings::AddPopStateListener(id);
        return id;
    }

    void RemovePopStateListener(std::int32_t id) {
        Crafter::DomBindings::RemovePopStateListener(id);
        Crafter::DomBindings::PopStateUnregister(id);
    }

    std::string GetPath() {
        const char* raw = Crafter::DomBindings::GetPathName();
        if (!raw) return {};
        std::string out(raw);
        std::free(const_cast<char*>(raw));
        return out;
    }
}
