// ============================================================
// components/admin/ObjectiveMappingPanel.jsx
// Redesigned: "Objective Translations" — Rosetta Stone layout
//
// Primary: Interactive coverage matrix (objectives × channels)
// Secondary: Objective cards with channel translation blocks
// ============================================================
import React, { useState, useMemo, useCallback, memo } from 'react';
import { useObjectiveMappings, PROVIDER_OBJECTIVES } from '../../context/ObjectiveMappingsContext';

// ── Styles ──
const styles = {
    panel: {
        padding: '24px',
        maxWidth: '1200px',
    },
    header: {
        display: 'flex',
        justifyContent: 'space-between',
        alignItems: 'flex-start',
        marginBottom: '24px',
        flexWrap: 'wrap',
        gap: '12px',
    },
    headerLeft: {
        display: 'flex',
        flexDirection: 'column',
        gap: '4px',
    },
    title: {
        fontSize: '20px',
        fontWeight: 600,
        color: '#111827',
        margin: 0,
    },
    subtitle: {
        fontSize: '13px',
        color: '#6B7280',
        margin: 0,
    },
    statsRow: {
        display: 'flex',
        gap: '16px',
        alignItems: 'center',
    },
    statBadge: (color) => ({
        display: 'inline-flex',
        alignItems: 'center',
        gap: '6px',
        padding: '4px 10px',
        borderRadius: '6px',
        fontSize: '12px',
        fontWeight: 500,
        background: color + '14',
        color: color,
    }),

    // ── Coverage matrix ──
    matrixSection: {
        marginBottom: '32px',
    },
    sectionTitle: {
        fontSize: '14px',
        fontWeight: 600,
        color: '#374151',
        marginBottom: '12px',
        display: 'flex',
        alignItems: 'center',
        gap: '8px',
    },
    matrixTable: {
        width: '100%',
        borderCollapse: 'separate',
        borderSpacing: '0',
        border: '1px solid #E5E7EB',
        borderRadius: '8px',
        overflow: 'hidden',
    },
    matrixTh: {
        padding: '10px 16px',
        fontSize: '12px',
        fontWeight: 600,
        textTransform: 'uppercase',
        letterSpacing: '0.05em',
        color: '#6B7280',
        background: '#F9FAFB',
        textAlign: 'center',
        borderBottom: '1px solid #E5E7EB',
    },
    matrixThLeft: {
        padding: '10px 16px',
        fontSize: '12px',
        fontWeight: 600,
        color: '#6B7280',
        background: '#F9FAFB',
        textAlign: 'left',
        borderBottom: '1px solid #E5E7EB',
        borderRight: '1px solid #E5E7EB',
    },
    matrixObjCell: (color) => ({
        padding: '10px 16px',
        borderBottom: '1px solid #E5E7EB',
        borderRight: '1px solid #E5E7EB',
        background: '#fff',
        display: 'flex',
        alignItems: 'center',
        gap: '8px',
    }),
    objDot: (color) => ({
        width: '8px',
        height: '8px',
        borderRadius: '50%',
        background: color,
        flexShrink: 0,
    }),
    matrixCell: (filled) => ({
        padding: '8px',
        borderBottom: '1px solid #E5E7EB',
        borderRight: '1px solid #E5E7EB',
        textAlign: 'center',
        cursor: 'pointer',
        transition: 'background 0.15s',
        background: filled ? '#F0FDF4' : '#fff',
        verticalAlign: 'middle',
    }),
    matrixCellFilled: {
        fontSize: '11px',
        fontWeight: 500,
        color: '#065F46',
        lineHeight: '1.3',
    },
    matrixCellEmpty: {
        color: '#D1D5DB',
        fontSize: '18px',
    },

    // ── Objective cards ──
    cardsSection: {
        display: 'flex',
        flexDirection: 'column',
        gap: '16px',
    },
    card: {
        border: '1px solid #E5E7EB',
        borderRadius: '10px',
        overflow: 'hidden',
        background: '#fff',
    },
    cardHeader: (color) => ({
        display: 'flex',
        alignItems: 'center',
        justifyContent: 'space-between',
        padding: '14px 20px',
        borderBottom: '1px solid #E5E7EB',
        background: color + '08',
        borderLeft: `4px solid ${color}`,
    }),
    cardTitle: {
        display: 'flex',
        alignItems: 'center',
        gap: '10px',
    },
    cardTitleText: {
        fontSize: '15px',
        fontWeight: 600,
        color: '#111827',
        textTransform: 'capitalize',
    },
    cardCount: (color) => ({
        fontSize: '11px',
        padding: '2px 8px',
        borderRadius: '10px',
        background: color + '1A',
        color: color,
        fontWeight: 500,
    }),
    cardBody: {
        display: 'flex',
        gap: '0',
        flexWrap: 'wrap',
    },

    // ── Translation block ──
    translationBlock: (channelColor) => ({
        flex: '1 1 280px',
        padding: '16px 20px',
        borderRight: '1px solid #F3F4F6',
        borderBottom: '1px solid #F3F4F6',
        position: 'relative',
    }),
    translationHeader: {
        display: 'flex',
        justifyContent: 'space-between',
        alignItems: 'center',
        marginBottom: '8px',
    },
    channelLabel: (color) => ({
        fontSize: '12px',
        fontWeight: 600,
        color: color,
        display: 'flex',
        alignItems: 'center',
        gap: '6px',
    }),
    providerValue: {
        fontSize: '13px',
        fontWeight: 500,
        color: '#111827',
        marginBottom: '4px',
    },
    providerLabel: {
        fontSize: '12px',
        color: '#6B7280',
        marginBottom: '10px',
    },
    capsRow: {
        display: 'flex',
        gap: '6px',
        flexWrap: 'wrap',
        marginBottom: '6px',
    },
    capBadge: (supported) => ({
        fontSize: '10px',
        fontWeight: 500,
        padding: '2px 7px',
        borderRadius: '4px',
        background: supported ? '#ECFDF5' : '#F9FAFB',
        color: supported ? '#065F46' : '#9CA3AF',
        border: `1px solid ${supported ? '#D1FAE5' : '#E5E7EB'}`,
    }),
    notes: {
        fontSize: '11px',
        color: '#9CA3AF',
        fontStyle: 'italic',
        marginTop: '4px',
    },
    blockActions: {
        display: 'flex',
        gap: '6px',
    },
    iconBtn: {
        background: 'none',
        border: 'none',
        cursor: 'pointer',
        padding: '2px 4px',
        fontSize: '13px',
        color: '#9CA3AF',
        borderRadius: '4px',
        transition: 'color 0.15s, background 0.15s',
    },
    addTranslationBlock: {
        flex: '1 1 280px',
        padding: '16px 20px',
        display: 'flex',
        alignItems: 'center',
        justifyContent: 'center',
        borderRight: '1px solid #F3F4F6',
        borderBottom: '1px solid #F3F4F6',
        minHeight: '80px',
    },
    addBtn: {
        background: 'none',
        border: '2px dashed #D1D5DB',
        borderRadius: '8px',
        padding: '8px 16px',
        color: '#9CA3AF',
        fontSize: '12px',
        fontWeight: 500,
        cursor: 'pointer',
        transition: 'all 0.15s',
        width: '100%',
    },

    // ── Form / modal ──
    overlay: {
        position: 'fixed',
        inset: 0,
        background: 'rgba(0,0,0,0.3)',
        display: 'flex',
        alignItems: 'center',
        justifyContent: 'center',
        zIndex: 1000,
    },
    formCard: {
        background: '#fff',
        borderRadius: '12px',
        width: '520px',
        maxHeight: '85vh',
        overflowY: 'auto',
        boxShadow: '0 20px 60px rgba(0,0,0,0.15)',
    },
    formHeader: {
        padding: '20px 24px',
        borderBottom: '1px solid #E5E7EB',
        display: 'flex',
        justifyContent: 'space-between',
        alignItems: 'center',
    },
    formTitle: {
        fontSize: '16px',
        fontWeight: 600,
        color: '#111827',
        margin: 0,
    },
    formBody: {
        padding: '20px 24px',
        display: 'flex',
        flexDirection: 'column',
        gap: '16px',
    },
    formFooter: {
        padding: '16px 24px',
        borderTop: '1px solid #E5E7EB',
        display: 'flex',
        justifyContent: 'flex-end',
        gap: '10px',
    },
    fieldGroup: {
        display: 'flex',
        flexDirection: 'column',
        gap: '4px',
    },
    fieldLabel: {
        fontSize: '12px',
        fontWeight: 600,
        color: '#374151',
    },
    fieldInput: {
        padding: '8px 12px',
        border: '1px solid #D1D5DB',
        borderRadius: '6px',
        fontSize: '13px',
        outline: 'none',
        transition: 'border-color 0.15s',
    },
    fieldSelect: {
        padding: '8px 12px',
        border: '1px solid #D1D5DB',
        borderRadius: '6px',
        fontSize: '13px',
        outline: 'none',
        background: '#fff',
    },
    checkRow: {
        display: 'flex',
        alignItems: 'center',
        gap: '8px',
    },
    checkLabel: {
        fontSize: '13px',
        color: '#374151',
    },
    btnPrimary: {
        padding: '8px 18px',
        background: '#2563EB',
        color: '#fff',
        border: 'none',
        borderRadius: '6px',
        fontSize: '13px',
        fontWeight: 500,
        cursor: 'pointer',
    },
    btnSecondary: {
        padding: '8px 18px',
        background: '#fff',
        color: '#374151',
        border: '1px solid #D1D5DB',
        borderRadius: '6px',
        fontSize: '13px',
        fontWeight: 500,
        cursor: 'pointer',
    },
    btnDanger: {
        padding: '8px 18px',
        background: '#FEE2E2',
        color: '#DC2626',
        border: '1px solid #FECACA',
        borderRadius: '6px',
        fontSize: '13px',
        fontWeight: 500,
        cursor: 'pointer',
    },
    loading: {
        padding: '60px',
        textAlign: 'center',
        color: '#9CA3AF',
        fontSize: '14px',
    },
    error: {
        padding: '16px',
        background: '#FEF2F2',
        border: '1px solid #FECACA',
        borderRadius: '8px',
        color: '#DC2626',
        fontSize: '13px',
    },
    emptyState: {
        padding: '40px',
        textAlign: 'center',
        color: '#9CA3AF',
        fontSize: '14px',
        border: '2px dashed #E5E7EB',
        borderRadius: '8px',
    },
};

// ── Capability labels ──
const CAPABILITY_FLAGS = [
    { key: 'supportsObjectiveChange',  short: 'Objective',  label: 'Change Objective' },
    { key: 'supportsBudgetChange',     short: 'Budget',     label: 'Change Budget' },
    { key: 'supportsTargetingChange',  short: 'Targeting',  label: 'Change Targeting' },
    { key: 'supportsStatusToggle',     short: 'Status',     label: 'Toggle Status' },
];

// ════════════════════════════════════════════════════════════
// Main Panel
// ════════════════════════════════════════════════════════════
export default function ObjectiveMappingPanel() {
    const {
        channels, objectives, mappings, channelMap, objectiveColorMap,
        coverageMatrix, coverageStats, loading, metaError,
        createMapping, updateMapping, deleteMapping, getProviderObjectives,
    } = useObjectiveMappings();

    const [formState, setFormState] = useState(null); // null | { mode: 'create'|'edit', presets?, mapping? }

    const activeChannels = useMemo(() => channels.filter(c => c.isActive), [channels]);
    const activeObjectives = useMemo(
        () => objectives.filter(o => o.isActive).sort((a, b) => a.sortOrder - b.sortOrder),
        [objectives],
    );

    // ── Open form helpers ──
    const openCreate = useCallback((presets = {}) => {
        setFormState({ mode: 'create', presets });
    }, []);

    const openEdit = useCallback((mapping) => {
        setFormState({ mode: 'edit', mapping });
    }, []);

    const closeForm = useCallback(() => setFormState(null), []);

    // ── Loading / error ──
    if (loading) {
        return <div style={styles.loading}>Loading objective translations...</div>;
    }

    if (metaError) {
        return <div style={styles.error}>Error loading metadata: {metaError}</div>;
    }

    return (
        <div style={styles.panel}>
            {/* ── Header ── */}
            <div style={styles.header}>
                <div style={styles.headerLeft}>
                    <h2 style={styles.title}>Objective Translations</h2>
                    <p style={styles.subtitle}>
                        Maps platform objectives to provider-specific campaign types across channels
                    </p>
                </div>
                <div style={styles.statsRow}>
                    <span style={styles.statBadge('#10B981')}>
                        {coverageStats.filled} mapped
                    </span>
                    {coverageStats.gaps > 0 && (
                        <span style={styles.statBadge('#EF4444')}>
                            {coverageStats.gaps} gap{coverageStats.gaps !== 1 ? 's' : ''}
                        </span>
                    )}
                    <span style={styles.statBadge('#6B7280')}>
                        {coverageStats.pct}% coverage
                    </span>
                </div>
            </div>

            {/* ── Coverage Matrix ── */}
            <div style={styles.matrixSection}>
                <div style={styles.sectionTitle}>
                    <span>Coverage Matrix</span>
                    <span style={{ fontSize: '11px', color: '#9CA3AF', fontWeight: 400 }}>
                        Click any cell to {'\u00B7'} add or edit
                    </span>
                </div>
                <CoverageMatrix
                    objectives={activeObjectives}
                    channels={activeChannels}
                    matrix={coverageMatrix}
                    colorMap={objectiveColorMap}
                    onClickCell={(objective, channel, mapping) => {
                        if (mapping) {
                            openEdit(mapping);
                        } else {
                            openCreate({ channelType: channel.code, platformObjective: objective.name });
                        }
                    }}
                />
            </div>

            {/* ── Objective Cards ── */}
            <div style={styles.sectionTitle}>
                <span>Translations by Objective</span>
            </div>
            <div style={styles.cardsSection}>
                {activeObjectives.map(obj => (
                    <ObjectiveCard
                        key={obj.name}
                        objective={obj}
                        channels={activeChannels}
                        channelMap={channelMap}
                        matrix={coverageMatrix}
                        colorMap={objectiveColorMap}
                        onEdit={openEdit}
                        onAdd={(channelCode) => openCreate({
                            platformObjective: obj.name,
                            channelType: channelCode,
                        })}
                        onDelete={deleteMapping}
                    />
                ))}
                {activeObjectives.length === 0 && (
                    <div style={styles.emptyState}>
                        No active objectives defined. Add objectives in the Allocation Templates panel.
                    </div>
                )}
            </div>

            {/* ── Form overlay ── */}
            {formState && (
                <MappingFormOverlay
                    mode={formState.mode}
                    presets={formState.presets}
                    mapping={formState.mapping}
                    channels={activeChannels}
                    objectives={activeObjectives}
                    getProviderObjectives={getProviderObjectives}
                    onCreate={createMapping}
                    onUpdate={updateMapping}
                    onClose={closeForm}
                />
            )}
        </div>
    );
}

// ════════════════════════════════════════════════════════════
// Coverage Matrix (table)
// ════════════════════════════════════════════════════════════
const CoverageMatrix = memo(function CoverageMatrix({ objectives, channels, matrix, colorMap, onClickCell }) {
    if (!objectives.length || !channels.length) {
        return <div style={styles.emptyState}>Add channels and objectives to see the coverage matrix</div>;
    }

    return (
        <table style={styles.matrixTable}>
            <thead>
                <tr>
                    <th style={styles.matrixThLeft}>Objective</th>
                    {channels.map(ch => (
                        <th key={ch.code} style={styles.matrixTh}>
                            <span style={{ color: ch.color || '#6B7280' }}>
                                {ch.icon || ''} {ch.label}
                            </span>
                        </th>
                    ))}
                </tr>
            </thead>
            <tbody>
                {objectives.map(obj => {
                    const color = colorMap[obj.name] || '#6B7280';
                    return (
                        <tr key={obj.name}>
                            <td style={{ borderBottom: '1px solid #E5E7EB', borderRight: '1px solid #E5E7EB', padding: '10px 16px', background: '#fff' }}>
                                <div style={{ display: 'flex', alignItems: 'center', gap: '8px' }}>
                                    <span style={styles.objDot(color)} />
                                    <span style={{ fontSize: '13px', fontWeight: 500, color: '#111827', textTransform: 'capitalize' }}>
                                        {obj.name}
                                    </span>
                                </div>
                            </td>
                            {channels.map(ch => {
                                const mapping = matrix[obj.name]?.[ch.code];
                                return (
                                    <td
                                        key={ch.code}
                                        style={styles.matrixCell(!!mapping)}
                                        onClick={() => onClickCell(obj, ch, mapping)}
                                        onMouseEnter={e => { e.currentTarget.style.background = mapping ? '#DCFCE7' : '#F3F4F6'; }}
                                        onMouseLeave={e => { e.currentTarget.style.background = mapping ? '#F0FDF4' : '#fff'; }}
                                        title={mapping
                                            ? `${mapping.providerObjectiveLabel}\nClick to edit`
                                            : `No mapping — click to add`
                                        }
                                    >
                                        {mapping ? (
                                            <div style={styles.matrixCellFilled}>
                                                {mapping.providerObjectiveLabel || mapping.providerObjective}
                                            </div>
                                        ) : (
                                            <div style={styles.matrixCellEmpty}>+</div>
                                        )}
                                    </td>
                                );
                            })}
                        </tr>
                    );
                })}
            </tbody>
        </table>
    );
});

// ════════════════════════════════════════════════════════════
// Objective Card
// ════════════════════════════════════════════════════════════
const ObjectiveCard = memo(function ObjectiveCard({
    objective, channels, channelMap, matrix, colorMap, onEdit, onAdd, onDelete,
}) {
    const color = colorMap[objective.name] || '#6B7280';
    const row = matrix[objective.name] || {};
    const filledChannels = channels.filter(ch => row[ch.code]);
    const missingChannels = channels.filter(ch => !row[ch.code]);
    const [confirmDelete, setConfirmDelete] = useState(null);

    const handleDelete = async (mappingId) => {
        const result = await onDelete(mappingId);
        if (result?.ok) setConfirmDelete(null);
    };

    return (
        <div style={styles.card}>
            <div style={styles.cardHeader(color)}>
                <div style={styles.cardTitle}>
                    <span style={styles.objDot(color)} />
                    <span style={styles.cardTitleText}>{objective.name}</span>
                    <span style={styles.cardCount(color)}>
                        {filledChannels.length}/{channels.length} channels
                    </span>
                </div>
            </div>
            <div style={styles.cardBody}>
                {/* Filled translations */}
                {filledChannels.map(ch => {
                    const mapping = row[ch.code];
                    const chMeta = channelMap[ch.code] || {};
                    const chColor = chMeta.color || '#6B7280';

                    return (
                        <div key={ch.code} style={styles.translationBlock(chColor)}>
                            <div style={styles.translationHeader}>
                                <div style={styles.channelLabel(chColor)}>
                                    {chMeta.icon || ''} {chMeta.label || ch.code}
                                </div>
                                <div style={styles.blockActions}>
                                    <button
                                        style={styles.iconBtn}
                                        onClick={() => onEdit(mapping)}
                                        title="Edit"
                                        onMouseEnter={e => { e.target.style.color = '#2563EB'; }}
                                        onMouseLeave={e => { e.target.style.color = '#9CA3AF'; }}
                                    >
                                        ✏️
                                    </button>
                                    {confirmDelete === mapping.mappingId ? (
                                        <>
                                            <button
                                                style={{ ...styles.iconBtn, color: '#DC2626', fontSize: '11px' }}
                                                onClick={() => handleDelete(mapping.mappingId)}
                                            >
                                                Confirm
                                            </button>
                                            <button
                                                style={{ ...styles.iconBtn, fontSize: '11px' }}
                                                onClick={() => setConfirmDelete(null)}
                                            >
                                                Cancel
                                            </button>
                                        </>
                                    ) : (
                                        <button
                                            style={styles.iconBtn}
                                            onClick={() => setConfirmDelete(mapping.mappingId)}
                                            title="Delete"
                                            onMouseEnter={e => { e.target.style.color = '#DC2626'; }}
                                            onMouseLeave={e => { e.target.style.color = '#9CA3AF'; }}
                                        >
                                            🗑️
                                        </button>
                                    )}
                                </div>
                            </div>
                            <div style={styles.providerValue}>
                                {mapping.providerObjective}
                            </div>
                            <div style={styles.providerLabel}>
                                {mapping.providerObjectiveLabel}
                            </div>
                            <div style={styles.capsRow}>
                                {CAPABILITY_FLAGS.map(cap => (
                                    <span key={cap.key} style={styles.capBadge(mapping[cap.key])}>
                                        {mapping[cap.key] ? '✓' : '✗'} {cap.short}
                                    </span>
                                ))}
                            </div>
                            {mapping.notes && (
                                <div style={styles.notes}>{mapping.notes}</div>
                            )}
                        </div>
                    );
                })}

                {/* Missing channel slots */}
                {missingChannels.map(ch => {
                    const chMeta = channelMap[ch.code] || {};
                    return (
                        <div key={ch.code} style={styles.addTranslationBlock}>
                            <button
                                style={styles.addBtn}
                                onClick={() => onAdd(ch.code)}
                                onMouseEnter={e => {
                                    e.target.style.borderColor = '#9CA3AF';
                                    e.target.style.color = '#374151';
                                }}
                                onMouseLeave={e => {
                                    e.target.style.borderColor = '#D1D5DB';
                                    e.target.style.color = '#9CA3AF';
                                }}
                            >
                                + Add {chMeta.label || ch.code} translation
                            </button>
                        </div>
                    );
                })}
            </div>
        </div>
    );
});

// ════════════════════════════════════════════════════════════
// Mapping Form Overlay (create / edit)
// ════════════════════════════════════════════════════════════
function MappingFormOverlay({
    mode, presets, mapping, channels, objectives,
    getProviderObjectives, onCreate, onUpdate, onClose,
}) {
    const isEdit = mode === 'edit';
    const initial = isEdit ? mapping : (presets || {});

    const [form, setForm] = useState({
        channelType:              initial.channelType || '',
        platformObjective:        initial.platformObjective || '',
        providerObjective:        initial.providerObjective || '',
        providerObjectiveLabel:   initial.providerObjectiveLabel || '',
        supportsObjectiveChange:  initial.supportsObjectiveChange ?? false,
        supportsBudgetChange:     initial.supportsBudgetChange ?? true,
        supportsTargetingChange:  initial.supportsTargetingChange ?? true,
        supportsStatusToggle:     initial.supportsStatusToggle ?? true,
        notes:                    initial.notes || '',
    });
    const [saving, setSaving] = useState(false);
    const [error, setError] = useState(null);

    const providerOpts = useMemo(
        () => getProviderObjectives(form.channelType),
        [form.channelType, getProviderObjectives],
    );

    const handleChange = (field, value) => {
        setForm(prev => ({ ...prev, [field]: value }));

        // Auto-fill label when picking from provider objective dropdown
        if (field === 'providerObjective') {
            const opt = providerOpts.find(o => o.value === value);
            if (opt) {
                setForm(prev => ({ ...prev, providerObjective: value, providerObjectiveLabel: opt.label }));
            }
        }
    };

    const handleSubmit = async () => {
        setError(null);
        if (!form.channelType || !form.platformObjective || !form.providerObjective || !form.providerObjectiveLabel) {
            setError('All required fields must be filled');
            return;
        }

        setSaving(true);
        try {
            let result;
            if (isEdit) {
                result = await onUpdate(mapping.mappingId, form);
            } else {
                result = await onCreate(form);
            }
            if (result?.ok) {
                onClose();
            } else {
                setError(result?.error || 'Operation failed');
            }
        } catch (err) {
            setError(err.message);
        } finally {
            setSaving(false);
        }
    };

    return (
        <div style={styles.overlay} onClick={onClose}>
            <div style={styles.formCard} onClick={e => e.stopPropagation()}>
                {/* Header */}
                <div style={styles.formHeader}>
                    <h3 style={styles.formTitle}>
                        {isEdit ? 'Edit Translation' : 'Add Translation'}
                    </h3>
                    <button style={styles.iconBtn} onClick={onClose}>✕</button>
                </div>

                {/* Body */}
                <div style={styles.formBody}>
                    {error && <div style={styles.error}>{error}</div>}

                    {/* Channel */}
                    <div style={styles.fieldGroup}>
                        <label style={styles.fieldLabel}>Channel *</label>
                        <select
                            style={styles.fieldSelect}
                            value={form.channelType}
                            onChange={e => handleChange('channelType', e.target.value)}
                            disabled={isEdit}
                        >
                            <option value="">Select channel...</option>
                            {channels.map(ch => (
                                <option key={ch.code} value={ch.code}>{ch.label}</option>
                            ))}
                        </select>
                    </div>

                    {/* Platform Objective */}
                    <div style={styles.fieldGroup}>
                        <label style={styles.fieldLabel}>Platform Objective *</label>
                        <select
                            style={styles.fieldSelect}
                            value={form.platformObjective}
                            onChange={e => handleChange('platformObjective', e.target.value)}
                            disabled={isEdit}
                        >
                            <option value="">Select objective...</option>
                            {objectives.map(obj => (
                                <option key={obj.name} value={obj.name}>{obj.name}</option>
                            ))}
                        </select>
                    </div>

                    {/* Provider Objective */}
                    <div style={styles.fieldGroup}>
                        <label style={styles.fieldLabel}>Provider Objective *</label>
                        {providerOpts.length > 0 ? (
                            <select
                                style={styles.fieldSelect}
                                value={form.providerObjective}
                                onChange={e => handleChange('providerObjective', e.target.value)}
                            >
                                <option value="">Select provider objective...</option>
                                {providerOpts.map(opt => (
                                    <option key={opt.value} value={opt.value}>{opt.label} ({opt.value})</option>
                                ))}
                            </select>
                        ) : (
                            <input
                                style={styles.fieldInput}
                                value={form.providerObjective}
                                onChange={e => handleChange('providerObjective', e.target.value)}
                                placeholder="e.g. MAXIMIZE_CONVERSIONS"
                            />
                        )}
                    </div>

                    {/* Provider Objective Label */}
                    <div style={styles.fieldGroup}>
                        <label style={styles.fieldLabel}>Provider Objective Label *</label>
                        <input
                            style={styles.fieldInput}
                            value={form.providerObjectiveLabel}
                            onChange={e => handleChange('providerObjectiveLabel', e.target.value)}
                            placeholder="Human-readable label"
                        />
                    </div>

                    {/* Capability Flags */}
                    <div style={styles.fieldGroup}>
                        <label style={styles.fieldLabel}>Capability Flags</label>
                        <div style={{ display: 'flex', flexDirection: 'column', gap: '8px', marginTop: '4px' }}>
                            {CAPABILITY_FLAGS.map(cap => (
                                <label key={cap.key} style={styles.checkRow}>
                                    <input
                                        type="checkbox"
                                        checked={form[cap.key] || false}
                                        onChange={e => handleChange(cap.key, e.target.checked)}
                                    />
                                    <span style={styles.checkLabel}>{cap.label}</span>
                                </label>
                            ))}
                        </div>
                    </div>

                    {/* Notes */}
                    <div style={styles.fieldGroup}>
                        <label style={styles.fieldLabel}>Notes</label>
                        <input
                            style={styles.fieldInput}
                            value={form.notes}
                            onChange={e => handleChange('notes', e.target.value)}
                            placeholder="Optional notes..."
                        />
                    </div>
                </div>

                {/* Footer */}
                <div style={styles.formFooter}>
                    <button style={styles.btnSecondary} onClick={onClose} disabled={saving}>
                        Cancel
                    </button>
                    <button style={styles.btnPrimary} onClick={handleSubmit} disabled={saving}>
                        {saving ? 'Saving...' : isEdit ? 'Update' : 'Create'}
                    </button>
                </div>
            </div>
        </div>
    );
}
