/**
 * p11Chart.js - The Universal Transporter (V4)
 * Optimized for AOT-Safe Data Models and ES-Module import.
 */
export const P11ChartFunctions = {
    _instances: new Map(),

    _getThemeColors: function () {
        const style = getComputedStyle(document.documentElement);
        return {
            primary: style.getPropertyValue('--bs-primary').trim() || '#0d6efd',
            text: style.getPropertyValue('--bs-body-color').trim() || '#212529',
            grid: style.getPropertyValue('--bs-border-color').trim() || 'rgba(0,0,0,0.1)',
            paper: style.getPropertyValue('--tpc-bg-paper').trim() || '#ffffff'
        };
    },

    /**
     * Prepares the config for Chart.js by flattening the AOT-safe 'styles' nodes 
     * back into the dataset objects.
     */
    _flattenConfig: function (config) {
        if (config && config.data && config.data.datasets) {
            config.data.datasets.forEach(dataset => {
                if (dataset.styles) {
                    // Kopiert alle Properties aus dem 'styles' Objekt direkt in das Dataset
                    Object.assign(dataset, dataset.styles);
                    // Löscht das Hilfsobjekt, um die Chart.js Struktur sauber zu halten
                    delete dataset.styles;
                }
            });
        }
        return config;
    },

    /**
     * Internal helper to attach the click and hover logic.
     */
    _applyInteractions: function (instanceId, config) {
        if (config && config.options) {
            config.options.onClick = (event, elements, chart) => {
                if (elements && elements.length > 0) {
                    const firstPoint = elements[0];
                    const datasetIndex = firstPoint.datasetIndex;
                    const dataIndex = firstPoint.index;

                    if (window.p11Js?.log) {
                        window.p11Js.log("Chart", `Click detected on ${instanceId}. Dataset: ${datasetIndex}, Index: ${dataIndex}`);
                    }

                    if (window.p11Js && window.p11Js.chartEventRef) {
                        window.p11Js.chartEventRef.invokeMethodAsync(
                            'HandleChartClick',
                            instanceId,
                            datasetIndex,
                            dataIndex
                        );
                    }
                }
            };

            config.options.onHover = (event, elements) => {
                if (event && event.native && event.native.target) {
                    event.native.target.style.cursor = (elements && elements.length > 0) ? 'pointer' : 'default';
                }
            };
        }
    },

    /**
     * Initializes a new Chart.js instance.
     */
    initialize: function (instanceId, canvas, config, dotNetRef) {
        if (window.p11Js?.log) {
            window.p11Js.log("Chart", `Initialize V4 called for ID: ${instanceId}`);
        }

        if (!canvas) return;

        if (this._instances.has(instanceId)) {
            this.dispose(instanceId);
        }

        // AOT-Struktur glätten & Interaktionen binden
        const finalConfig = this._flattenConfig(config);
        this._applyInteractions(instanceId, finalConfig);

        try {
            const chartInstance = new Chart(canvas, {
                type: finalConfig.type,
                data: finalConfig.data,
                options: finalConfig.options
            });

            this._instances.set(instanceId, {
                chart: chartInstance,
                dotNetRef: dotNetRef
            });

            if (window.p11Js?.log) {
                window.p11Js.log("Chart", `SUCCESS: Instance '${instanceId}' initialized.`);
            }
        } catch (e) {
            console.error("[p11][Chart] Init Error:", e);
        }
    },

    /**
     * Updates an existing chart with new data or options.
     */
    updateData: function (instanceId, config) {
        const state = this._instances.get(instanceId);
        if (state && state.chart) {
            // Auch beim Update: AOT-Struktur glätten
            const finalConfig = this._flattenConfig(config);
            this._applyInteractions(instanceId, finalConfig);

            state.chart.data = finalConfig.data;
            state.chart.options = finalConfig.options;
            state.chart.update();

            if (window.p11Js?.log) {
                window.p11Js.log("Chart", `Update successful for: ${instanceId}`);
            }
        }
    },

    /**
     * Cleans up the instance.
     */
    dispose: function (instanceId) {
        const state = this._instances.get(instanceId);
        if (state) {
            if (state.chart) {
                state.chart.destroy();
            }
            this._instances.delete(instanceId);
        }
    }
};

///**
// * p11Chart.js - The Universal Transporter (V3)
// * Optimized for ES-Module import via p11.js Orchestrator.
// */
//export const P11ChartFunctions = {
//    _instances: new Map(),

//    _getThemeColors: function () {
//        const style = getComputedStyle(document.documentElement);
//        return {
//            primary: style.getPropertyValue('--bs-primary').trim() || '#0d6efd',
//            text: style.getPropertyValue('--bs-body-color').trim() || '#212529',
//            grid: style.getPropertyValue('--bs-border-color').trim() || 'rgba(0,0,0,0.1)',
//            paper: style.getPropertyValue('--tpc-bg-paper').trim() || '#ffffff'
//        };
//    },

//    /**
//     * Internal helper to attach the click and hover logic.
//     * This ensures the JS-Function is re-applied even after C# updates the options object.
//     */
//    _applyInteractions: function (instanceId, config) {
//        if (config && config.options) {
//            config.options.onClick = (event, elements, chart) => {
//                if (elements && elements.length > 0) {
//                    const firstPoint = elements[0];
//                    const datasetIndex = firstPoint.datasetIndex;
//                    const dataIndex = firstPoint.index;

//                    if (window.p11Js?.log) {
//                        window.p11Js.log("Chart", `Click detected on ${instanceId}. Dataset: ${datasetIndex}, Index: ${dataIndex}`);
//                    }

//                    // WICHTIG: Wir nutzen den dedizierten Chart-Slot in der Bridge
//                    if (window.p11Js && window.p11Js.chartEventRef) {
//                        window.p11Js.chartEventRef.invokeMethodAsync(
//                            'HandleChartClick',
//                            instanceId, // Die stabile GUID
//                            datasetIndex,
//                            dataIndex
//                        );
//                    }
//                }
//            };

//            // Cursor-Styling für bessere UX
//            config.options.onHover = (event, elements) => {
//                if (event && event.native && event.native.target) {
//                    event.native.target.style.cursor = (elements && elements.length > 0) ? 'pointer' : 'default';
//                }
//            };
//        }
//    },

//    /**
//     * Initializes a new Chart.js instance.
//     * Called via window.p11Js.Chart.initialize
//     */
//    initialize: function (instanceId, canvas, config, dotNetRef) {
//        if (window.p11Js?.log) {
//            window.p11Js.log("Chart", `Initialize called for ID: ${instanceId}`);
//        }

//        if (!canvas) {
//            if (window.p11Js?.log) {
//                window.p11Js.log("Chart", `ERROR: Canvas element is null for ID: ${instanceId}`);
//            }
//            return;
//        }

//        // Cleanup falls Instanz bereits existiert
//        if (this._instances.has(instanceId)) {
//            if (window.p11Js?.log) {
//                window.p11Js.log("Chart", `Cleaning up existing instance: ${instanceId}`);
//            }
//            this.dispose(instanceId);
//        }

//        const colors = this._getThemeColors();

//        // 1. Click-Handling Integration (Brücke zum EventStateService)
//        this._applyInteractions(instanceId, config);

//        try {
//            if (window.p11Js?.log) {
//                window.p11Js.log("Chart", `Attempting to create Chart.js instance for ${instanceId} with type: ${config.type}`);
//            }

//            const chartInstance = new Chart(canvas, {
//                type: config.type,
//                data: config.data,
//                options: config.options
//            });

//            this._instances.set(instanceId, {
//                chart: chartInstance,
//                dotNetRef: dotNetRef
//            });

//            if (window.p11Js?.log) {
//                window.p11Js.log("Chart", `SUCCESS: Instance '${instanceId}' fully initialized.`);
//            }
//        } catch (e) {
//            if (window.p11Js?.log) {
//                window.p11Js.log("Chart", `CRITICAL: Init Error for ${instanceId}: ${e.message}`);
//            }
//            console.error("[p11][Chart] Critical Init Error:", e);
//        }
//    },

//    updateData: function (instanceId, config) {
//        if (window.p11Js?.log) {
//            window.p11Js.log("Chart", `Updating data for instance: ${instanceId}`);
//        }

//        const state = this._instances.get(instanceId);
//        if (state && state.chart) {
//            // WICHTIG: C# schickt neue Options (wo onClick null ist). 
//            // Wir müssen unsere JS-Funktion hier erneut einhängen!
//            this._applyInteractions(instanceId, config);

//            state.chart.data = config.data;
//            state.chart.options = config.options;
//            state.chart.update();

//            if (window.p11Js?.log) {
//                window.p11Js.log("Chart", `Update successful for: ${instanceId}`);
//            }
//        } else {
//            if (window.p11Js?.log) {
//                window.p11Js.log("Chart", `Update FAILED: Instance ${instanceId} not found.`);
//            }
//        }
//    },

//    dispose: function (instanceId) {
//        if (window.p11Js?.log) {
//            window.p11Js.log("Chart", `Disposing instance: ${instanceId}`);
//        }

//        const state = this._instances.get(instanceId);
//        if (state) {
//            if (state.chart) {
//                state.chart.destroy();
//            }
//            this._instances.delete(instanceId);

//            if (window.p11Js?.log) {
//                window.p11Js.log("Chart", `Dispose successful for: ${instanceId}`);
//            }
//        }
//    }
//};