import React, { useState } from 'react';

const DAY_NAMES = ['월', '화', '수', '목', '금', '토'];

export default function TrialsGrid({ trials, perDay, winnerTrialId }) {
    const [expanded, setExpanded] = useState(null);

    const byDow = {};
    for (const t of trials || []) byDow[t.day_of_week] = t;

    const perDayByDow = {};
    for (const d of perDay || []) perDayByDow[d.day_of_week] = d;

    const maxScore = Math.max(...(perDay || []).map(d => d.avg_score || 0), 0.001);

    return (
        <div className="evolver-card trials-grid">
            <h2>이번주 6일 Trials</h2>
            <div className="grid">
                {DAY_NAMES.map((name, dow) => {
                    const trial = byDow[dow];
                    const day = perDayByDow[dow];
                    const isWinner = trial && trial.id === winnerTrialId;
                    const heightPct = day ? (day.avg_score / maxScore) * 100 : 0;
                    return (
                        <button
                            key={dow}
                            type="button"
                            className={`trial-cell ${isWinner ? 'winner' : ''} ${expanded === dow ? 'expanded' : ''}`}
                            onClick={() => setExpanded(expanded === dow ? null : dow)}
                        >
                            <div className="bar" style={{ height: `${heightPct}%` }} />
                            <span className="label">{name}{isWinner && '⭐'}</span>
                            {day && <span className="max-correct">max={day.max_correct}</span>}
                        </button>
                    );
                })}
            </div>
            {expanded !== null && byDow[expanded] && (
                <div className="trial-detail">
                    <h3>{DAY_NAMES[expanded]}요일 상세</h3>
                    <p>W = [{(byDow[expanded].weight || []).map(w => w.toFixed(2)).join(', ')}]</p>
                    <ul>
                        {(byDow[expanded].picks || []).map(p => (
                            <li key={p.id}>
                                {(p.numbers || []).join(', ')} —
                                score {(p.meta_score || 0).toFixed(3)}
                                {p.correct != null && ` · 적중 ${p.correct}개`}
                            </li>
                        ))}
                    </ul>
                </div>
            )}
        </div>
    );
}
