import { useEffect, useMemo, useState } from 'react';
import RetrospectiveBox from './RetrospectiveBox';
import TierModeToggle, { MODES } from './TierModeToggle';
import TierSection from './TierSection';
import BulkPurchaseButton from './BulkPurchaseButton';
import './decision.css';

const TIER_CHAIN = {
    core: ['core'],
    core_bonus: ['core', 'bonus'],
    core_bonus_extended: ['core', 'bonus', 'extended'],
    full: ['core', 'bonus', 'extended', 'pool'],
};

const STORAGE_KEY = 'lotto.tier_mode';

export default function DecisionCard({ briefing, review, onPurchaseSuccess }) {
    const [tierMode, setTierMode] = useState(() =>
        localStorage.getItem(STORAGE_KEY) || 'core'
    );

    useEffect(() => {
        localStorage.setItem(STORAGE_KEY, tierMode);
    }, [tierMode]);

    const visibleTiers = TIER_CHAIN[tierMode];

    const totalSets = useMemo(
        () => visibleTiers.reduce((sum, t) => sum + (briefing?.picks?.[t]?.length || 0), 0),
        [briefing, visibleTiers]
    );

    // 분배 칩 — 보이는 계층의 risk_tag 합산
    const balance = useMemo(() => {
        const acc = { '안정': 0, '균형': 0, '공격': 0 };
        for (const t of visibleTiers) {
            for (const p of (briefing?.picks?.[t] || [])) {
                if (acc[p.risk_tag] !== undefined) acc[p.risk_tag]++;
            }
        }
        return acc;
    }, [briefing, visibleTiers]);

    if (!briefing) return null;

    let cursor = 0;

    return (
        <div className="lc-card">
            <header className="lc-head">
                <div>
                    <p className="lc-eyebrow">Curator Briefing · {briefing.draw_no}회</p>
                    <h3 className="lc-title">{briefing.narrative.headline}</h3>
                </div>
                <div className="lc-conf">
                    <div className="lc-conf__num">{briefing.confidence}</div>
                    <div className="lc-conf__lbl">CONFIDENCE</div>
                </div>
            </header>

            <RetrospectiveBox briefing={briefing} review={review} />

            <p className="lc-headline-3">
                {(briefing.narrative.summary_3lines || []).join(' · ')}
            </p>

            <div className="lc-balance">
                <div className="lc-balance__chips">
                    {balance['안정'] > 0 && <span className="lc-chip lc-chip--stable">안정 ×{balance['안정']}</span>}
                    {balance['균형'] > 0 && <span className="lc-chip lc-chip--balance">균형 ×{balance['균형']}</span>}
                    {balance['공격'] > 0 && <span className="lc-chip lc-chip--aggro">공격 ×{balance['공격']}</span>}
                </div>
            </div>

            <TierModeToggle value={tierMode} onChange={setTierMode} />

            {visibleTiers.map(tier => {
                const picks = briefing.picks?.[tier] || [];
                const idxBase = cursor;
                cursor += picks.length;
                return (
                    <TierSection
                        key={tier}
                        tier={tier}
                        picks={picks}
                        rationale={briefing.tier_rationale?.[tier]}
                        indexBase={idxBase}
                        totalSets={totalSets}
                    />
                );
            })}

            <div className="lc-actions">
                <BulkPurchaseButton
                    drawNo={briefing.draw_no}
                    tierMode={tierMode}
                    onSuccess={onPurchaseSuccess}
                />
            </div>
        </div>
    );
}
