import * as d3 from 'd3';
import '/src/css/style.css';
import 'bootstrap';
import { StackedBarChartHelper } from './charts-helpers/stacked-bar-chart-helper';
import { MultiLineChartHelper } from './charts-helpers/multi-line-chart-helper';
import { PieChartHelper } from './charts-helpers/pie-chart-helper';
import { PloarAreaChartHelper } from './charts-helpers/polar-area-chart-helper';

const datasetPath = import.meta.env.VITE_DATASET_PATH;
let rawData: any[];
const stackerBarChartHelper = new StackedBarChartHelper();
const multiLineChartHelper = new MultiLineChartHelper();
const pieChartHelper = new PieChartHelper();
const polarChartHelper = new PloarAreaChartHelper();

d3.csv(datasetPath).then(data => {
    rawData = data.filter(d => d.Medal !== '');
    rawData = data.filter(d => d.Year !== '');
    rawData = data.filter(d => d.Medal !== '');
    stackerBarChartHelper.setData(rawData);
    stackerBarChartHelper.appendChart();

    multiLineChartHelper.setData(rawData);
    multiLineChartHelper.appendChart();

    pieChartHelper.setData(rawData);
    pieChartHelper.appendChart();

    polarChartHelper.setData(rawData);
    polarChartHelper.appendChart();

});

// Attach event listeners to buttons
document.addEventListener('DOMContentLoaded', () => {
    const buttons = [
        { id: 'btnCountry', chartId: 'medalDistributionByCountryChart' },
        { id: 'btnTrend', chartId: 'medalDistributionByTimeChart' },
        { id: 'btnGender', chartId: 'medalDistributionByGenderChart' },
        { id: 'btnSport', chartId: 'medalDistributionBySportChart' }
    ];

    buttons.forEach(({ id, chartId }) => {
        const button = document.getElementById(id);
        if (button) {
            button.addEventListener('click', () => showChart(chartId, button));
        }
    });
});

function showChart(chartId: string, button: HTMLElement) {
    // Hide all charts
    d3.selectAll('.chart').style('display', 'none');

    // Show the selected chart
    const selectedChart = d3.select(`#${chartId}`);
    if (!selectedChart.empty()) {
        selectedChart.style('display', 'block');
    }

    // Enable all buttons and disable the clicked one
    d3.selectAll('.btn')
        .classed('disabled', false)
        .property('disabled', false);

    // Disable the clicked button
    d3.select(button)
        .classed('disabled', true)
        .property('disabled', true);

    // Scroll to the end of the page
    window.scrollTo({
        top: document.body.scrollHeight,
        behavior: 'smooth'
    });
}