/**
 * Plotly Utilities
 * Shared functions for Plotly chart rendering and management
 */

/**
 * Default Plotly layout for dark theme
 */
export const defaultPlotlyLayout = {
    plot_bgcolor: 'transparent',
    paper_bgcolor: 'transparent',
    font: { family: 'Inter, -apple-system, BlinkMacSystemFont, sans-serif', size: 12, color: '#f1f5f9' },
    colorway: ['#3b82f6','#22c55e','#eab308','#ef4444','#8b5cf6','#06b6d4','#f59e0b','#10b981'],
    margin: { l: 60, r: 50, t: 50, b: 60 },
    showlegend: true,
    legend: {
        orientation: 'v',
        x: 1.02,
        y: 1,
        xanchor: 'left',
        yanchor: 'top',
        bgcolor: 'rgba(30, 41, 59, 0.9)',
        bordercolor: '#475569',
        borderwidth: 1,
        font: { size: 10, color: '#f1f5f9' }
    },
    xaxis: { gridcolor: '#334155', zerolinecolor: '#475569', color: '#cbd5e1', fixedrange: false },
    yaxis: { gridcolor: '#334155', zerolinecolor: '#475569', color: '#cbd5e1', fixedrange: false },
    autosize: true,
    width: null,
    height: null
};

/**
 * Default Plotly config
 */
export const defaultPlotlyConfig = {
    displayModeBar: true,
    modeBarButtonsToRemove: ['select2d','lasso2d','hoverClosestCartesian','hoverCompareCartesian','toggleSpikelines'],
    displaylogo: false,
    responsive: false,
    doubleClick: 'reset',
    toImageButtonOptions: { format: 'png', filename: 'vna_chart', height: 600, width: 800, scale: 1 }
};

/**
 * Setup resize observer for Plotly plot
 * @param {HTMLElement} container - Plot container element
 */
export function setupPlotlyResize(container) {
    if (!window.ResizeObserver || !container) return;

    const ro = new ResizeObserver(() => {
        if (container && container.clientWidth > 0 && typeof Plotly !== 'undefined') {
            Plotly.Plots.resize(container);
        }
    });
    ro.observe(container);
    container._resizeObserver = ro;
}

/**
 * Cleanup Plotly plot and observers
 * @param {HTMLElement} container - Plot container element
 */
export function cleanupPlotly(container) {
    if (!container) return;

    if (container._resizeObserver) {
        container._resizeObserver.disconnect();
        container._resizeObserver = null;
    }

    if (container._fullData && typeof Plotly !== 'undefined') {
        Plotly.purge(container);
    }
}

/**
 * Create Plotly plot with default styling
 * @param {HTMLElement} container - Container element
 * @param {Array} data - Plotly data traces
 * @param {Object} layoutOverrides - Layout overrides
 * @param {Object} configOverrides - Config overrides
 */
export function createPlotlyPlot(container, data = [], layoutOverrides = {}, configOverrides = {}) {
    if (!container || typeof Plotly === 'undefined') return;

    const layout = {
        ...defaultPlotlyLayout,
        ...layoutOverrides
    };

    const config = {
        ...defaultPlotlyConfig,
        ...configOverrides
    };

    Plotly.newPlot(container, data, layout, config);
    setupPlotlyResize(container);
}

/**
 * Update existing Plotly plot
 * @param {HTMLElement} container - Container element
 * @param {Array} data - Plotly data traces
 * @param {Object} layoutOverrides - Layout overrides
 * @param {Object} configOverrides - Config overrides
 */
export async function updatePlotlyPlot(container, data = [], layoutOverrides = {}, configOverrides = {}) {
    if (!container || typeof Plotly === 'undefined') return;

    const layout = {
        ...defaultPlotlyLayout,
        ...layoutOverrides
    };

    // Remove width/height to allow autosize
    delete layout.width;
    delete layout.height;

    const config = {
        ...defaultPlotlyConfig,
        ...configOverrides
    };

    await Plotly.react(container, data, layout, config);
}

/**
 * Toggle fullscreen for element with Plotly plot
 * @param {HTMLElement} element - Element to fullscreen
 * @param {HTMLElement} plotContainer - Plot container inside element
 */
export async function togglePlotlyFullscreen(element, plotContainer) {
    if (!element || typeof Plotly === 'undefined') return;

    if (!document.fullscreenElement) {
        try {
            await element.requestFullscreen?.();
            setTimeout(() => {
                if (plotContainer) {
                    const rect = plotContainer.getBoundingClientRect();
                    Plotly.relayout(plotContainer, { width: rect.width, height: rect.height });
                    Plotly.Plots.resize(plotContainer);
                }
            }, 200);
        } catch (error) {
            console.error('Fullscreen request failed:', error);
        }
    } else {
        try {
            await document.exitFullscreen?.();
            setTimeout(() => {
                if (plotContainer) {
                    Plotly.Plots.resize(plotContainer);
                }
            }, 100);
        } catch (error) {
            console.error('Exit fullscreen failed:', error);
        }
    }
}

/**
 * Download Plotly plot as image
 * @param {HTMLElement} container - Plot container
 * @param {string} filename - Output filename (without extension)
 * @param {Object} options - Download options
 */
export async function downloadPlotlyImage(container, filename = 'plot', options = {}) {
    if (!container || typeof Plotly === 'undefined') return;

    const defaultOptions = {
        format: 'png',
        width: 1200,
        height: 800,
        filename
    };

    await Plotly.downloadImage(container, { ...defaultOptions, ...options });
}