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

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

        // 1. Initialize store
        const initialSprings = JSON.parse(this.el.dataset.initialSprings || "[]");

        const [state, setState] = createStore({
            springs: initialSprings,
            rivers: {}, // Map spring_id -> rivers
            streams: {}, // Map river_id -> streams
            trenches: {}, // Map stream_id -> trenches
            activeSpringId: null,
            activeRiverId: null,
            activeStreamId: null
        });

        // 2. Render parameters
        this._cleanup = render(() => (
            <HierarchyApp
                state={state}
                push={(e, p) => this.pushEvent(e, p)}
                setState={setState}
            />
        ), this.el);

        // 3. Listen for server assignments
        this.handleEvent("update_rivers", ({ spring_id, rivers }) => {
            setState("rivers", spring_id, rivers);
        });

        this.handleEvent("update_streams", ({ river_id, streams }) => {
            setState("streams", river_id, streams);
        });

        this.handleEvent("update_trenches", ({ stream_id, trenches }) => {
            setState("trenches", stream_id, trenches);
        });
    },

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