import { WebviewWindow } from "@tauri-apps/api/webviewWindow";

export async function openChartWindow(
    chartId: string,
    theme: "dark" | "light",
    title: string,
    scope: "GLOBAL" | "CLIMATE" | "METEO" = "GLOBAL",
    channel: "maincharts" | "climatecharts" | "meteocharts" = "maincharts",
) {
    const label = `${channel}-${chartId}`;

    const existing = await WebviewWindow.getByLabel(label);

    if (existing) {
        await existing.show();
        await existing.setFocus();
        return;
    }

    const chartWindow = new WebviewWindow(label, {
        url: `/chart-window/${chartId}?theme=${theme}&scope=${scope}&channel=${channel}`,

        title,

        width: 920,
        height: 680,
        minWidth: 720,
        minHeight: 480,

        decorations: false,
        transparent: false,

        resizable: true,
        maximizable: true,
        minimizable: true,
        closable: true,

        visible: true,
        focus: true,
        center: true,

        skipTaskbar: false,
    });

    chartWindow.once("tauri://created", () => {
        console.log(`Chart window created: ${label}`);
    });

    chartWindow.once("tauri://error", (error) => {
        console.error(`Failed to create chart window: ${label}`, error);
    });

    return chartWindow;
}