import React, { useMemo } from 'react';
import { buildFrequencySeries } from '../lottoUtils';

const FrequencyChart = ({ stats }) => {
    const { series, max } = useMemo(() => buildFrequencySeries(stats?.frequency), [stats]);
    const ticks = useMemo(() => [max, Math.round(max * 0.5), 0], [max]);
    if (!stats) return null;

    return (
        <div className="lotto-chart">
            <div className="lotto-chart__y">
                <span>횟수</span>
                <div className="lotto-chart__ticks">
                    {ticks.map((value) => <span key={value}>{value}</span>)}
                </div>
            </div>
            <div className="lotto-chart__plot" role="list">
                {series.map((item) => {
                    const showLabel = item.number === 1 || item.number % 5 === 0;
                    return (
                        <div key={item.number} className="lotto-chart__col" role="listitem">
                            <span
                                className="lotto-chart__bar"
                                style={{ height: `${(item.count / max) * 100}%` }}
                                title={`${item.number}번: ${item.count}회`}
                                aria-label={`${item.number}번 ${item.count}회`}
                            />
                            <span className="lotto-chart__x" aria-hidden={!showLabel}>
                                {showLabel ? item.number : ''}
                            </span>
                        </div>
                    );
                })}
            </div>
        </div>
    );
};

export default FrequencyChart;
