import { render } from "solid-js/web";
import { createStore } from "solid-js/store";
import { SolidApp } from "../components/SolidApp";

export const SolidBridge = {
    mounted() {
        console.log("SolidBridge mounted");

        // 1. Initialize a reactive store with initial data from the element attributes
        const initialCount = parseInt(this.el.dataset.initialCount || "0");
        const [state, setState] = createStore({
            count: initialCount
        });

        // 2. Render Solid and pass the 'push' helper
        // We store the cleanup function to call on destroyed()
        this._cleanup = render(() => (
            <SolidApp
                state={state}
                push={(e, p) => this.pushEvent(e, p)}
            />
        ), this.el);

        // 3. Sync server state to Solid store
        this.handleEvent("sync_state", (payload) => {
            console.log("Received sync_state:", payload);
            setState(payload);
        });
    },

    destroyed() {
        if (this._cleanup) {
            this._cleanup();
        }
    }
};
