import { NexusMarkerService } from "../../markers/services/NexusMarkerService.js";
import { SiteLabelManager } from "../../site/services/SiteLabelManager.js";
import { ShopStore } from "./ShopStore.js";

export class ShopCanvasBridge {
    static #registered = false;

    static registerHooks() {
        if (this.#registered) return;
        this.#registered = true;
        Hooks.on("dropCanvasData", (_canvas, data, event) => {
            if (data?.type !== "AugurNexusShop" || data?.kind !== "nexus-shop") return undefined;
            this.#place(data, event).catch(error => {
                console.error("Augur Nexus | Failed to place Shop marker.", error);
                ui.notifications.error("Could not place that Shop on the scene.");
            });
            return false;
        });
    }

    static async #place(data = {}, event = null) {
        if (!game.user?.isGM || !canvas?.scene) return null;
        const shop = ShopStore.getShop(data.shopId || data.uuid);
        if (!shop) return null;
        let x = Number(data.x);
        let y = Number(data.y);
        if ((!Number.isFinite(x) || !Number.isFinite(y)) && canvas.canvasCoordinatesFromClient) {
            const point = canvas.canvasCoordinatesFromClient({ x: Number(event?.clientX), y: Number(event?.clientY) });
            x = point.x;
            y = point.y;
        }
        if (!Number.isFinite(x) || !Number.isFinite(y) || !canvas.dimensions?.rect?.contains(x, y)) return null;
        const iconSize = Math.min(240, Math.max(32, Math.round(Number(canvas.grid?.size ?? canvas.dimensions?.size ?? NexusMarkerService.DEFAULT_ICON_SIZE))));
        const marker = await NexusMarkerService.createMarker({ kind: "nexus-shop", shopId: shop.id }, { x, y }, {
            iconSize,
            labelFontSize: SiteLabelManager.getDefaultFontSize(iconSize),
            snapToGrid: false
        });
        if (marker) {
            const { openNexusMarkerEditorForPlaceable } = await import("../../../support/toolbar/NexusToolContext.js");
            openNexusMarkerEditorForPlaceable(marker);
        }
        return marker;
    }
}
