import React, { useState, useRef, useEffect, memo } from 'react';
import Picker from '@emoji-mart/react';
import emojiData from '@emoji-mart/data';
import { useAdmin } from '../../context/AdminContext';
import { useTemplates, CHANNELS, CHANNEL_META } from '../../context/TemplatesContext';
import { GATEWAY_API_URL } from '../../auth/authConfig';

// ─── Helpers ────────────────────────────────────────────────
const fmt = (s) => (s || '').replace(/_/g, ' ').replace(/\b\w/g, c => c.toUpperCase());
const truncate = (str, max) => !str ? '—' : str.length > max ? str.substring(0, max) + '…' : str;


// ─── Donut Chart (SVG) — memoized ────────────────────────────
const DonutChart = memo(function DonutChart({ allocations, size = 110, thickness = 20 }) {
    const center = size / 2;
    const radius = (size - thickness) / 2;
    const total = allocations.reduce((s, a) => s + (a.recommendedPct || 0), 0);

    if (total === 0) {
        return (
            <svg width={size} height={size}>
                <circle cx={center} cy={center} r={radius} fill="none"
                    stroke="var(--border)" strokeWidth={thickness} />
            </svg>
        );
    }

    let cumulative = 0;
    const segments = allocations.map((a) => {
        const startAngle = (cumulative / total) * 2 * Math.PI - Math.PI / 2;
        cumulative += (a.recommendedPct || 0);
        const endAngle = (cumulative / total) * 2 * Math.PI - Math.PI / 2;
        const largeArc = (a.recommendedPct / total) * 360 > 180 ? 1 : 0;
        return {
            ...a,
            d: `M ${center + radius * Math.cos(startAngle)} ${center + radius * Math.sin(startAngle)} A ${radius} ${radius} 0 ${largeArc} 1 ${center + radius * Math.cos(endAngle)} ${center + radius * Math.sin(endAngle)}`
        };
    });

    const isBalanced = Math.abs(total - 100) < 0.01;

    return (
        <svg width={size} height={size} viewBox={`0 0 ${size} ${size}`}>
            {segments.map((seg, i) => (
                <path key={i} d={seg.d} fill="none"
                    stroke={CHANNEL_META[seg.channelType]?.color || '#999'}
                    strokeWidth={thickness} strokeLinecap="butt" />
            ))}
            <text x={center} y={center - 4} textAnchor="middle"
                style={{ fontSize: 15, fontWeight: 700, fill: isBalanced ? 'var(--success)' : 'var(--danger)' }}>
                {total}%
            </text>
            <text x={center} y={center + 12} textAnchor="middle"
                style={{ fontSize: 10, fill: 'var(--text-dim)' }}>
                total
            </text>
        </svg>
    );
});

// ─── Icon Picker Popover (emoji-mart) — memoized ─────────────
const IconPicker = memo(function IconPicker({ value, onChange }) {
    const [open, setOpen] = useState(false);
    const ref = useRef(null);
    const btnRef = useRef(null);
    const [above, setAbove] = useState(false);

    useEffect(() => {
        if (!open) return;
        const handler = (e) => { if (ref.current && !ref.current.contains(e.target)) setOpen(false); };
        document.addEventListener('mousedown', handler);
        return () => document.removeEventListener('mousedown', handler);
    }, [open]);

    useEffect(() => {
        if (open && btnRef.current) {
            const rect = btnRef.current.getBoundingClientRect();
            setAbove(rect.bottom + 360 > window.innerHeight);
        }
    }, [open]);

    return (
        <span ref={ref} style={{ position: 'relative' }}>
            <button ref={btnRef} onClick={(e) => { e.stopPropagation(); setOpen(!open); }}
                className="icon-picker-btn">{value}</button>
            {open && (
                <div className="icon-picker-popover" style={{ [above ? 'bottom' : 'top']: 34 }}>
                    <Picker
                        data={emojiData}
                        onEmojiSelect={(emoji) => { onChange(emoji.native); setOpen(false); }}
                        theme="light"
                        previewPosition="none"
                        skinTonePosition="search"
                        maxFrequentRows={1}
                        navPosition="bottom"
                        perLine={7}
                        emojiSize={22}
                        emojiButtonSize={30}
                    />
                </div>
            )}
        </span>
    );
});

// ─── Color Picker — memoized ────────────────────────────────
const ColorPicker = memo(function ColorPicker({ value, onChange }) {
    const [open, setOpen] = useState(false);
    const ref = useRef(null);
    const presets = ['#7dca7d','#4fc3f7','#ffb74d','#ce93d8','#ef5350','#90a4ae','#4db6ac','#ff8a65','#aed581','#7986cb'];

    useEffect(() => {
        if (!open) return;
        const handler = (e) => { if (ref.current && !ref.current.contains(e.target)) setOpen(false); };
        document.addEventListener('mousedown', handler);
        return () => document.removeEventListener('mousedown', handler);
    }, [open]);

    return (
        <span ref={ref} style={{ position: 'relative' }}>
            <button onClick={(e) => { e.stopPropagation(); setOpen(!open); }}
                className="color-picker-btn"
                style={{ backgroundColor: value || '#999' }} />
            {open && (
                <div className="color-picker-grid">
                    {presets.map(c => (
                        <button key={c}
                            className={`color-picker-option ${c === value ? 'active' : ''}`}
                            style={{ backgroundColor: c }}
                            onClick={(e) => { e.stopPropagation(); onChange(c); setOpen(false); }} />
                    ))}
                </div>
            )}
        </span>
    );
});

// ─── Channel Badge — memoized ───────────────────────────────
const ChannelBadge = memo(function ChannelBadge({ channel }) {
    const meta = CHANNEL_META[channel] || {};
    return (
        <span className="channel-badge" style={{ borderColor: meta.color || '#666' }}>
            {meta.label || channel}
        </span>
    );
});


// ─── Template Create/Edit Form — uses both contexts ─────────
const TemplateForm = memo(function TemplateForm({ editData, defaultCategory, defaultObjective, availableChannels, onSuccess, onCancel }) {
    const { apiCall } = useAdmin();
    const { categories, objectives } = useTemplates();

    const channelOptions = availableChannels || CHANNELS;
    const lockCatObj = !!availableChannels;
    const [channelType, setChannelType] = useState(editData?.channelType || (channelOptions.length === 1 ? channelOptions[0] : ''));
    const [businessCategory, setBusinessCategory] = useState(editData?.businessCategory || defaultCategory || '');
    const [objective, setObjective] = useState(editData?.objective || defaultObjective || '');
    const [recommendedPct, setRecommendedPct] = useState(editData?.recommendedPct ?? '');
    const [minBudgetRequired, setMinBudgetRequired] = useState(editData?.minBudgetRequired ?? 0);
    const [rationale, setRationale] = useState(editData?.rationale || '');
    const [isActive, setIsActive] = useState(editData?.isActive ?? true);
    const [loading, setLoading] = useState(false);
    const [error, setError] = useState(null);

    const isEdit = !!editData;
    const formTitle = lockCatObj
        ? `Add Channel to ${fmt(defaultCategory)} \u00B7 ${fmt(defaultObjective)}`
        : (isEdit ? 'Edit Template' : 'Create Template');

    const handleSubmit = async (e) => {
        e.preventDefault();
        setLoading(true);
        setError(null);

        const url = isEdit
            ? `/api/admin/templates/${editData.templateId}`
            : `/api/admin/templates`;

        const result = await apiCall(url, isEdit ? 'PUT' : 'POST', {
            channelType, businessCategory, objective,
            recommendedPct: parseFloat(recommendedPct),
            minBudgetRequired: parseFloat(minBudgetRequired) || 0,
            rationale: rationale || null,
            ...(isEdit ? { isActive } : {})
        });

        if (result.ok) onSuccess();
        else setError(result.error || 'Operation failed');
        setLoading(false);
    };

    return (
        <div className="admin-form">
            <h3>{formTitle}</h3>
            {error && <div className="error-message">{error}</div>}
            <form onSubmit={handleSubmit}>
                <div className="form-row-inline">
                    <div className="form-group">
                        <label>Channel</label>
                        <select value={channelType} onChange={e => setChannelType(e.target.value)} required disabled={loading}>
                            <option value="">Select…</option>
                            {channelOptions.map(c => <option key={c} value={c}>{CHANNEL_META[c]?.label || c}</option>)}
                        </select>
                    </div>
                    {!lockCatObj && (
                        <div className="form-group">
                            <label>Category</label>
                            <select value={businessCategory} onChange={e => setBusinessCategory(e.target.value)} required disabled={loading}>
                                <option value="">Select…</option>
                                {categories.map(c => <option key={c.name} value={c.name}>{c.icon} {fmt(c.name)}</option>)}
                            </select>
                        </div>
                    )}
                    {!lockCatObj && (
                        <div className="form-group">
                            <label>Objective</label>
                            <select value={objective} onChange={e => setObjective(e.target.value)} required disabled={loading}>
                                <option value="">Select…</option>
                                {objectives.map(o => <option key={o.name} value={o.name}>{fmt(o.name)}</option>)}
                            </select>
                        </div>
                    )}
                </div>
                <div className="form-row-inline">
                    <div className="form-group">
                        <label>Recommended %</label>
                        <input type="number" min="0" max="100" step="0.01" value={recommendedPct}
                            onChange={e => setRecommendedPct(e.target.value)} required disabled={loading} />
                    </div>
                    <div className="form-group">
                        <label>Min Budget ($)</label>
                        <input type="number" min="0" step="1" value={minBudgetRequired}
                            onChange={e => setMinBudgetRequired(e.target.value)} disabled={loading} />
                    </div>
                    {isEdit && (
                        <div className="form-group">
                            <label>Active</label>
                            <select value={isActive ? 'true' : 'false'} onChange={e => setIsActive(e.target.value === 'true')} disabled={loading}>
                                <option value="true">Yes</option>
                                <option value="false">No</option>
                            </select>
                        </div>
                    )}
                </div>
                <div className="form-row-inline">
                    <div className="form-group" style={{ flex: '1 1 100%' }}>
                        <label>Rationale</label>
                        <input type="text" maxLength="500" value={rationale}
                            onChange={e => setRationale(e.target.value)} disabled={loading}
                            placeholder="Why this allocation is recommended…" />
                    </div>
                </div>
                <div className="form-buttons">
                    <button type="button" className="btn-cancel" onClick={onCancel} disabled={loading}>Cancel</button>
                    <button type="submit" className="btn-primary" disabled={loading}>
                        {loading ? 'Saving...' : isEdit ? 'Update' : 'Create'}
                    </button>
                </div>
            </form>
        </div>
    );
});


// =============================================================
// MAIN COMPONENT — pure presentation, all state from context
// =============================================================
export default function TemplatesPanel() {
    const { refresh } = useAdmin();
    const {
        templates, categories, objectives,
        catIconMap, objColorMap, catCounts,
        filtered, grouped,
        selectedCategory, setSelectedCategory,
        selectedObjective, setSelectedObjective,
        editMode, setEditMode,
        showForm, setShowForm,
        editingId, setEditingId,
        addingToGroup, setAddingToGroup,
        showNewCat, setShowNewCat,
        newCatName, setNewCatName,
        newCatIcon, setNewCatIcon,
        handleUpdateCategory, handleDeleteCategory, handleCreateCategory,
        handleUpdateObjective, handleDeleteTemplate,
    } = useTemplates();

    const { sessionToken } = useAdmin();

    // ── Forecast Validation State ──
    const [validating, setValidating] = useState(null);  // "category|objective" key
    const [validationResults, setValidationResults] = useState({});  // keyed by "category|objective"

    const handleValidateWithApi = async (category, objective, currentTemplates) => {
        const key = `${category}|${objective}`;
        setValidating(key);

        try {
            const headers = { 'Content-Type': 'application/json' };
            if (sessionToken) headers['Authorization'] = `Bearer ${sessionToken}`;

            const res = await fetch(`${GATEWAY_API_URL}/api/forecast/channel-estimate`, {
                method: 'POST',
                headers,
                body: JSON.stringify({
                    objective,
                    businessCategory: category,
                    keywords: [category, objective],
                    monthlyBudget: 1500,  // benchmark budget for normalization
                    channels: currentTemplates.map(t => t.channelType),
                }),
            });
            const data = await res.json().catch(() => null);

            if (res.ok && data?.channels) {
                const apiAllocations = {};
                data.channels.forEach(ch => {
                    apiAllocations[ch.provider] = {
                        pct: ch.allocationPercent,
                        score: ch.qualityScore,
                        label: ch.strengthLabel,
                        impressions: ch.estimates?.impressions,
                        clicks: ch.estimates?.clicks,
                    };
                });
                setValidationResults(prev => ({ ...prev, [key]: { ok: true, apiAllocations, timestamp: Date.now() } }));
            } else {
                setValidationResults(prev => ({ ...prev, [key]: { ok: false, error: data?.error || 'Forecast unavailable' } }));
            }
        } catch (e) {
            setValidationResults(prev => ({ ...prev, [key]: { ok: false, error: e.message } }));
        }
        setValidating(null);
    };

    return (
        <div className="templates-layout">
            {/* ═══ SIDEBAR ═══ */}
            <aside className="templates-sidebar">
                {/* ── Categories ── */}
                <div className="sidebar-section">
                    <div className="sidebar-section-header">
                        <span className="sidebar-section-title">Categories</span>
                        <button className="btn-icon-sm" onClick={() => setEditMode(!editMode)}
                            title={editMode ? 'Done editing' : 'Edit categories'}>
                            {editMode ? '✓' : '✎'}
                        </button>
                    </div>
                    <div className="sidebar-list sidebar-list-scrollable">
                        {categories.map(cat => (
                            <div key={cat.categoryId || cat.name} className="sidebar-item-wrapper">
                                <button
                                    className={`sidebar-item ${selectedCategory === cat.name ? 'active' : ''}`}
                                    onClick={() => setSelectedCategory(cat.name)}>
                                    {editMode ? (
                                        <IconPicker value={cat.icon || '📋'}
                                            onChange={(icon) => handleUpdateCategory(cat.categoryId, { icon })} />
                                    ) : (
                                        <span className="sidebar-item-icon">{cat.icon || '📋'}</span>
                                    )}
                                    <span className="sidebar-item-label">{fmt(cat.name)}</span>
                                    <span className="sidebar-item-count">{catCounts[cat.name] || 0}</span>
                                </button>
                                {editMode && (
                                    <button
                                        className="btn-icon-xs btn-danger-icon"
                                        title={catCounts[cat.name] ? `Has ${catCounts[cat.name]} templates — remove them first` : 'Delete category'}
                                        disabled={!!catCounts[cat.name]}
                                        onClick={(e) => { e.stopPropagation(); handleDeleteCategory(cat.categoryId, cat.name); }}>
                                        ✕
                                    </button>
                                )}
                            </div>
                        ))}
                    </div>
                    {/* Add New — always visible */}
                    {!showNewCat ? (
                        <button className="sidebar-item sidebar-add-btn" onClick={() => setShowNewCat(true)}>
                            <span className="sidebar-item-icon">+</span>
                            <span className="sidebar-item-label">Add Category</span>
                        </button>
                    ) : (
                        <div className="sidebar-new-item">
                            <IconPicker value={newCatIcon || '📋'}
                                onChange={(icon) => setNewCatIcon(icon)} />
                            <input
                                value={newCatName}
                                onChange={e => setNewCatName(e.target.value)}
                                onKeyDown={e => e.key === 'Enter' && handleCreateCategory()}
                                placeholder="category_name"
                                autoFocus
                            />
                            <button className="btn-icon-xs" onClick={handleCreateCategory}>✓</button>
                            <button className="btn-icon-xs" onClick={() => { setShowNewCat(false); setNewCatName(''); setNewCatIcon(''); }}>✕</button>
                        </div>
                    )}
                </div>

                {/* ── Objectives ── */}
                <div className="sidebar-section">
                    <div className="sidebar-section-header">
                        <span className="sidebar-section-title">Objectives</span>
                    </div>
                    <div className="sidebar-list sidebar-list-scrollable">
                        <button
                            className={`sidebar-item ${selectedObjective === null ? 'active' : ''}`}
                            onClick={() => setSelectedObjective(null)}>
                            <span className="sidebar-color-dot" style={{ background: 'var(--text-dim)' }} />
                            <span className="sidebar-item-label">All Objectives</span>
                        </button>
                        {objectives.map(obj => (
                            <button key={obj.objectiveId || obj.name}
                                className={`sidebar-item ${selectedObjective === obj.name ? 'active' : ''}`}
                                onClick={() => setSelectedObjective(selectedObjective === obj.name ? null : obj.name)}>
                                {editMode ? (
                                    <ColorPicker value={obj.color || '#999'}
                                        onChange={(color) => handleUpdateObjective(obj.objectiveId, { color })} />
                                ) : (
                                    <span className="sidebar-color-dot" style={{ background: obj.color || '#999' }} />
                                )}
                                <span className="sidebar-item-label">{fmt(obj.name)}</span>
                            </button>
                        ))}
                    </div>
                </div>
            </aside>

            {/* ═══ MAIN CONTENT ═══ */}
            <div className="templates-content">
                {/* Channel legend */}
                <div className="channel-legend-bar">
                    {CHANNELS.map(ch => (
                        <span key={ch} className="channel-chip" style={{ borderColor: CHANNEL_META[ch].color }}>
                            <span className="channel-chip-dot" style={{ background: CHANNEL_META[ch].color }} />
                            {CHANNEL_META[ch].label}
                        </span>
                    ))}
                </div>

                {/* Header */}
                <div className="panel-header">
                    <div>
                        <h2>
                            {selectedCategory ? fmt(selectedCategory) : 'Templates'}
                            {selectedObjective && <span className="header-objective-tag"
                                style={{ background: objColorMap[selectedObjective] || '#999' }}>
                                {fmt(selectedObjective)}
                            </span>}
                        </h2>
                        <span className="filter-count">{filtered.length} template{filtered.length !== 1 ? 's' : ''}</span>
                    </div>
                    <button className="btn-action" onClick={() => { setShowForm(!showForm); setEditingId(null); }}>
                        {showForm ? 'Cancel' : '+ Add Template'}
                    </button>
                </div>

                {/* Create/Edit form */}
                {showForm && (
                    <TemplateForm
                        defaultCategory={selectedCategory}
                        defaultObjective={selectedObjective}
                        onSuccess={() => { setShowForm(false); refresh(); }}
                        onCancel={() => setShowForm(false)}
                    />
                )}
                {editingId && (
                    <TemplateForm
                        editData={templates.find(t => t.templateId === editingId)}
                        onSuccess={() => { setEditingId(null); refresh(); }}
                        onCancel={() => setEditingId(null)}
                    />
                )}

                {/* Empty state */}
                {Object.keys(grouped).length === 0 && !showForm && (
                    <div className="empty-state">
                        <div className="empty-state-icon">📊</div>
                        <p>No templates for this combination yet.</p>
                        <p className="text-dim">Click "+ Add Template" to create one{selectedObjective ? ', or deselect the objective filter.' : '.'}</p>
                    </div>
                )}

                {/* Grouped template cards */}
                {Object.entries(grouped).map(([key, items]) => {
                    const [cat, obj] = key.split('|');
                    const totalPct = items.reduce((s, t) => s + (t.recommendedPct || 0), 0);
                    const isBalanced = Math.abs(totalPct - 100) < 0.01;

                    return (
                        <div key={key} className="template-group">
                            <div className="template-group-header">
                                <div className="template-group-info">
                                    <DonutChart allocations={items} />
                                    <div className="template-group-meta">
                                        <div className="template-group-title">
                                            <span className="cat-icon">{catIconMap[cat] || '📋'}</span>
                                            {fmt(cat)}
                                            <span className="objective-tag"
                                                style={{ background: objColorMap[obj] || '#999' }}>
                                                {fmt(obj)}
                                            </span>
                                        </div>
                                        <div className="template-group-stats">
                                            {items.length} channel{items.length !== 1 ? 's' : ''}
                                            {' · '}
                                            <span className={isBalanced ? 'text-success' : 'text-danger'}>
                                                {totalPct}% allocated {isBalanced ? '✓' : '⚠'}
                                            </span>
                                        </div>
                                        <div className="template-group-channel-bars">
                                            {items.map(t => (
                                                <div key={t.templateId} className="channel-bar">
                                                    <span className="channel-bar-color"
                                                        style={{ background: CHANNEL_META[t.channelType]?.color || '#999' }} />
                                                    <span className="channel-bar-label">{CHANNEL_META[t.channelType]?.label || t.channelType}</span>
                                                    <span className="channel-bar-pct">{t.recommendedPct}%</span>
                                                    <div className="channel-bar-track">
                                                        <div className="channel-bar-fill"
                                                            style={{
                                                                width: `${t.recommendedPct}%`,
                                                                background: CHANNEL_META[t.channelType]?.color || '#999'
                                                            }} />
                                                    </div>
                                                </div>
                                            ))}
                                        </div>
                                        {/* Validate with API button */}
                                        <button
                                            className="btn-small btn-validate"
                                            disabled={validating === key}
                                            onClick={() => handleValidateWithApi(cat, obj, items)}
                                            style={{ marginTop: 8 }}
                                        >
                                            {validating === key ? '⏳ Checking…' : '🔬 Validate with Forecast API'}
                                        </button>
                                    </div>
                                </div>
                            </div>

                            {/* API Validation Results */}
                            {validationResults[key] && (
                                <div className={`validation-results ${validationResults[key].ok ? '' : 'validation-error'}`}>
                                    {validationResults[key].ok ? (
                                        <>
                                            <div className="validation-header">
                                                <span>📊 API Forecast Comparison</span>
                                                <span className="text-dim" style={{ fontSize: 11 }}>
                                                    at $1,500/mo benchmark
                                                </span>
                                            </div>
                                            <div className="validation-comparison">
                                                {items.map(t => {
                                                    const api = validationResults[key].apiAllocations[t.channelType];
                                                    const diff = api ? (api.pct - t.recommendedPct) : null;
                                                    return (
                                                        <div key={t.templateId} className="validation-row">
                                                            <span className="channel-bar-color" style={{ background: CHANNEL_META[t.channelType]?.color || '#999' }} />
                                                            <span className="validation-ch">{CHANNEL_META[t.channelType]?.label || t.channelType}</span>
                                                            <span className="validation-template">{t.recommendedPct}%</span>
                                                            <span className="validation-arrow">→</span>
                                                            <span className={`validation-api ${diff && Math.abs(diff) > 5 ? 'validation-divergent' : ''}`}>
                                                                {api ? `${api.pct}%` : '—'}
                                                            </span>
                                                            {diff != null && Math.abs(diff) > 0 && (
                                                                <span className={`validation-diff ${diff > 0 ? 'text-success' : 'text-danger'}`}>
                                                                    {diff > 0 ? '+' : ''}{diff}%
                                                                </span>
                                                            )}
                                                        </div>
                                                    );
                                                })}
                                            </div>
                                        </>
                                    ) : (
                                        <div className="validation-error-msg">
                                            ⚠️ {validationResults[key].error}
                                        </div>
                                    )}
                                </div>
                            )}

                            <table className="data-table">
                                <thead>
                                    <tr>
                                        <th>Channel</th>
                                        <th>Allocation %</th>
                                        <th>Min Budget</th>
                                        <th>Rationale</th>
                                        <th>Active</th>
                                        <th>Actions</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    {items.sort((a, b) => (b.recommendedPct || 0) - (a.recommendedPct || 0)).map(t => (
                                        <tr key={t.templateId} className={!t.isActive ? 'row-inactive' : ''}>
                                            <td><ChannelBadge channel={t.channelType} /></td>
                                            <td className="number-cell">{t.recommendedPct}%</td>
                                            <td className="number-cell">${t.minBudgetRequired}</td>
                                            <td className="rationale-cell" title={t.rationale || ''}>
                                                {truncate(t.rationale, 50)}
                                            </td>
                                            <td>{t.isActive ? '✓' : '—'}</td>
                                            <td>
                                                <button className="btn-small" onClick={() => setEditingId(t.templateId)}>Edit</button>
                                                {' '}
                                                <button className="btn-small btn-danger"
                                                    onClick={() => handleDeleteTemplate(t.templateId)}>Delete</button>
                                            </td>
                                        </tr>
                                    ))}
                                </tbody>
                            </table>

                            {/* Add Channel */}
                            {(() => {
                                const usedChannels = items.map(t => t.channelType);
                                const missing = CHANNELS.filter(c => !usedChannels.includes(c));
                                if (missing.length === 0) return null;

                                const isAdding = addingToGroup?.category === cat && addingToGroup?.objective === obj;
                                return isAdding ? (
                                    <TemplateForm
                                        defaultCategory={cat}
                                        defaultObjective={obj}
                                        availableChannels={missing}
                                        onSuccess={() => { setAddingToGroup(null); refresh(); }}
                                        onCancel={() => setAddingToGroup(null)}
                                    />
                                ) : (
                                    <button className="btn-small btn-add-channel"
                                        onClick={() => setAddingToGroup({ category: cat, objective: obj })}>
                                        + Add Channel ({missing.map(c => CHANNEL_META[c]?.label || c).join(', ')})
                                    </button>
                                );
                            })()}
                        </div>
                    );
                })}

                {/* Allocation Summary */}
                {Object.keys(grouped).length > 0 && (
                    <div className="allocation-summary">
                        <h3>Allocation Summary</h3>
                        <div className="summary-grid">
                            {Object.entries(grouped).map(([key, items]) => {
                                const [cat, obj] = key.split('|');
                                const totalPct = items.reduce((s, t) => s + (t.recommendedPct || 0), 0);
                                const isBalanced = Math.abs(totalPct - 100) < 0.01;
                                return (
                                    <div key={key} className={`summary-item ${isBalanced ? '' : 'summary-warning'}`}>
                                        <span className="summary-label">
                                            {catIconMap[cat] || '📋'} {fmt(cat)} / {fmt(obj)}
                                        </span>
                                        <span className={`summary-pct ${isBalanced ? 'summary-ok' : 'summary-bad'}`}>
                                            {totalPct}%
                                        </span>
                                    </div>
                                );
                            })}
                        </div>
                    </div>
                )}
            </div>
        </div>
    );
}
