import { reactive } from 'vue';

// ── Palette block definitions ──────────────────────────────────────────────
// Content blocks are ported 1:1 from EmailEditor's palette (same icons, same
// box-model styling system). Field blocks are new - see isFieldBlock() below.
export const CONTENT_PALETTE_ITEMS = [
    { type: 'heading', label: 'Title', icon: '<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round" width="22" height="22"><path d="M4 12h8"/><path d="M4 18V6"/><path d="M12 18V6"/><path d="m17 12 3-2v8"/><path d="M16 18h5"/></svg>' },
    { type: 'logo', label: 'Logo', icon: '<svg xmlns="http://www.w3.org/2000/svg" width="22" height="22" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M21 16V8a2 2 0 0 0-1-1.73l-7-4a2 2 0 0 0-2 0l-7 4A2 2 0 0 0 3 8v8a2 2 0 0 0 1 1.73l7 4a2 2 0 0 0 2 0l7-4A2 2 0 0 0 21 16z"/></svg>' },
    { type: 'text', label: 'Text', icon: '<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round" width="22" height="22"><line x1="21" x2="3" y1="6" y2="6"/><line x1="15" x2="3" y1="12" y2="12"/><line x1="17" x2="3" y1="18" y2="18"/></svg>' },
    { type: 'image', label: 'Image', icon: '<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round" width="22" height="22"><rect width="18" height="18" x="3" y="3" rx="2" ry="2"/><circle cx="9" cy="9" r="2"/><path d="m21 15-3.08-3.08a2 2 0 0 0-2.82 0L6 21"/></svg>' },
    { type: 'button', label: 'Link Button', icon: '<svg xmlns="http://www.w3.org/2000/svg" width="22" height="22" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M14 4.1 12 6"/><path d="m5.1 8-2.9-.8"/><path d="m6 12-1.9 2"/><path d="M7.2 2.2 8 5.1"/><path d="M9.037 9.69a.498.498 0 0 1 .653-.653l11 4.5a.5.5 0 0 1-.074.949l-4.349 1.041a1 1 0 0 0-.74.739l-1.04 4.35a.5.5 0 0 1-.95.074z"/></svg>' },
    { type: 'divider', label: 'Divider', icon: '<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round" width="22" height="22"><line x1="5" x2="19" y1="12" y2="12"/></svg>' },
    { type: 'column', label: 'Columns', icon: '<svg xmlns="http://www.w3.org/2000/svg" width="22" height="22" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><rect width="18" height="18" x="3" y="3" rx="2"/><path d="M12 3v18"/></svg>' },
    { type: 'spacer', label: 'Spacer', icon: '<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round" width="22" height="22"><path d="m7 15 5 5 5-5"/><path d="m7 9 5-5 5 5"/></svg>' },
    { type: 'html', label: 'HTML', icon: '<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round" width="22" height="22"><path d="m18 16 4-4-4-4"/><path d="m6 8-4 4 4 4"/><path d="m14.5 4-5 16"/></svg>' },
];

export const FIELD_PALETTE_ITEMS = [
    { type: 'field-text', label: 'Short Text', icon: '<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8" width="22" height="22"><path stroke-linecap="round" stroke-linejoin="round" d="M3.75 6.75h16.5M3.75 12h16.5m-16.5 5.25H12"/></svg>' },
    { type: 'field-textarea', label: 'Long Text', icon: '<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8" width="22" height="22"><path stroke-linecap="round" stroke-linejoin="round" d="M3.75 6.75h16.5M3.75 12h16.5M3.75 17.25h16.5"/></svg>' },
    { type: 'field-email', label: 'Email', icon: '<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8" width="22" height="22"><path stroke-linecap="round" stroke-linejoin="round" d="M21.75 6.75v10.5a2.25 2.25 0 01-2.25 2.25h-15a2.25 2.25 0 01-2.25-2.25V6.75m19.5 0A2.25 2.25 0 0019.5 4.5h-15a2.25 2.25 0 00-2.25 2.25m19.5 0v.243a2.25 2.25 0 01-1.07 1.916l-7.5 4.615a2.25 2.25 0 01-2.36 0L3.32 8.91a2.25 2.25 0 01-1.07-1.916V6.75"/></svg>' },
    { type: 'field-phone', label: 'Phone', icon: '<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8" width="22" height="22"><path stroke-linecap="round" stroke-linejoin="round" d="M2.25 6.75c0 8.284 6.716 15 15 15h2.25a2.25 2.25 0 002.25-2.25v-1.372c0-.516-.351-.966-.852-1.091l-4.423-1.106c-.44-.11-.902.055-1.173.417l-.97 1.293c-.282.376-.769.542-1.21.38a12.035 12.035 0 01-7.143-7.143c-.162-.441.004-.928.38-1.21l1.293-.97c.363-.271.527-.734.417-1.173L6.963 3.102a1.125 1.125 0 00-1.091-.852H4.5A2.25 2.25 0 002.25 4.5v2.25z"/></svg>' },
    { type: 'field-name', label: 'Full Name', icon: '<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8" width="22" height="22"><path stroke-linecap="round" stroke-linejoin="round" d="M15.75 6a3.75 3.75 0 11-7.5 0 3.75 3.75 0 017.5 0zM4.501 20.118a7.5 7.5 0 0114.998 0A17.933 17.933 0 0112 21.75c-2.676 0-5.216-.584-7.499-1.632z"/></svg>' },
    { type: 'field-number', label: 'Number', icon: '<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8" width="22" height="22"><path stroke-linecap="round" stroke-linejoin="round" d="M6.429 9.75L2.25 12l4.179 2.25m0-4.5l5.571 3 5.571-3m-11.142 0L2.25 7.5 12 2.25l9.75 5.25-4.179 2.25m0 0L21.75 12l-4.179 2.25m0 0l4.179 2.25L12 21.75 2.25 16.5l4.179-2.25m11.142 0l-5.571 3-5.571-3"/></svg>' },
    { type: 'field-date', label: 'Date', icon: '<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8" width="22" height="22"><path stroke-linecap="round" stroke-linejoin="round" d="M6.75 3v2.25M17.25 3v2.25M3 18.75V7.5a2.25 2.25 0 012.25-2.25h13.5A2.25 2.25 0 0121 7.5v11.25m-18 0A2.25 2.25 0 005.25 21h13.5A2.25 2.25 0 0021 18.75m-18 0v-7.5A2.25 2.25 0 015.25 9h13.5A2.25 2.25 0 0121 11.25v7.5"/></svg>' },
    { type: 'field-website', label: 'Website', icon: '<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8" width="22" height="22"><path stroke-linecap="round" stroke-linejoin="round" d="M13.19 8.688a4.5 4.5 0 011.242 7.244l-4.5 4.5a4.5 4.5 0 01-6.364-6.364l1.757-1.757m13.35-.622l1.757-1.757a4.5 4.5 0 00-6.364-6.364l-4.5 4.5a4.5 4.5 0 001.242 7.244"/></svg>' },
    { type: 'field-dropdown', label: 'Dropdown', icon: '<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8" width="22" height="22"><path stroke-linecap="round" stroke-linejoin="round" d="M19.5 8.25l-7.5 7.5-7.5-7.5"/></svg>' },
    { type: 'field-radio', label: 'Choice', icon: '<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8" width="22" height="22"><path stroke-linecap="round" stroke-linejoin="round" d="M8.625 12a.375.375 0 11-.75 0 .375.375 0 01.75 0zm0 0H8.25m4.125 0a.375.375 0 11-.75 0 .375.375 0 01.75 0zm0 0H12m4.125 0a.375.375 0 11-.75 0 .375.375 0 01.75 0zm0 0h-.375M21 12a9 9 0 11-18 0 9 9 0 0118 0z"/></svg>' },
    { type: 'field-checkbox', label: 'Checkboxes', icon: '<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8" width="22" height="22"><path stroke-linecap="round" stroke-linejoin="round" d="M9 12.75L11.25 15 15 9.75M21 12a9 9 0 11-18 0 9 9 0 0118 0z"/></svg>' },
    { type: 'field-rating', label: 'Rating', icon: '<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8" width="22" height="22"><path stroke-linecap="round" stroke-linejoin="round" d="M11.48 3.499a.562.562 0 011.04 0l2.125 5.111a.563.563 0 00.475.345l5.518.442c.499.04.701.663.321.988l-4.204 3.602a.563.563 0 00-.182.557l1.285 5.385a.562.562 0 01-.84.61l-4.725-2.885a.563.563 0 00-.586 0L6.982 20.54a.562.562 0 01-.84-.61l1.285-5.386a.562.562 0 00-.182-.557l-4.204-3.602a.563.563 0 01.321-.988l5.518-.442a.563.563 0 00.475-.345L11.48 3.5z"/></svg>' },
    { type: 'field-consent', label: 'Consent', icon: '<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8" width="22" height="22"><path stroke-linecap="round" stroke-linejoin="round" d="M9 12.75L11.25 15 15 9.75m-3-7.036A11.959 11.959 0 013.598 6 11.99 11.99 0 003 9.749c0 5.592 3.824 10.29 9 11.623 5.176-1.332 9-6.03 9-11.622 0-1.31-.21-2.571-.598-3.751h-.152c-3.196 0-6.1-1.248-8.25-3.285z"/></svg>' },
    { type: 'field-hidden', label: 'Hidden', icon: '<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8" width="22" height="22"><path stroke-linecap="round" stroke-linejoin="round" d="M3.98 8.223A10.477 10.477 0 001.934 12C3.226 16.338 7.244 19.5 12 19.5c.993 0 1.953-.138 2.863-.395M6.228 6.228A10.45 10.45 0 0112 4.5c4.756 0 8.773 3.162 10.065 7.498a10.523 10.523 0 01-4.293 5.774M6.228 6.228L3 3m3.228 3.228l3.65 3.65m7.894 7.894L21 21m-3.228-3.228l-3.65-3.65m0 0a3 3 0 10-4.243-4.243m4.242 4.242L9.88 9.88"/></svg>' },
    { type: 'submit-button', label: 'Submit Button', icon: '<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" width="22" height="22"><path stroke-linecap="round" stroke-linejoin="round" d="M4.5 12.75l6 6 9-13.5"/></svg>' },
];

export const PALETTE_ITEMS = [...CONTENT_PALETTE_ITEMS, ...FIELD_PALETTE_ITEMS];

export const COLUMN_PALETTE_PRESETS = [
    { label: '1', columnCount: 1, colWidths: [100] },
    { label: '2', columnCount: 2, colWidths: [50, 50] },
    { label: '3', columnCount: 3, colWidths: [33.3, 33.3, 33.3] },
    { label: '1:2', columnCount: 2, colWidths: [33.3, 66.7] },
    { label: '2:1', columnCount: 2, colWidths: [66.7, 33.3] },
];

const DEFAULT_OPTIONS = {
    'field-radio': ['Option 1', 'Option 2', 'Option 3'],
    'field-checkbox': ['Option 1', 'Option 2'],
    'field-dropdown': ['Option 1', 'Option 2', 'Option 3'],
};

const DEFAULT_CONTACT_FIELD = { 'field-email': 'email', 'field-phone': 'phone' };

const FIELD_DEFAULT_LABEL = {
    'field-text': 'Short Text', 'field-textarea': 'Long Text', 'field-email': 'Email Address',
    'field-phone': 'Phone Number', 'field-name': 'Full Name', 'field-number': 'Number',
    'field-date': 'Date', 'field-website': 'Website URL', 'field-dropdown': 'Dropdown',
    'field-radio': 'Choose one', 'field-checkbox': 'Select all that apply', 'field-rating': 'Rating',
    'field-consent': 'Consent', 'field-hidden': 'Hidden field',
};

const FIELD_DEFAULT_PLACEHOLDER = {
    'field-text': 'Enter text…', 'field-textarea': 'Enter message…', 'field-email': 'you@example.com',
    'field-phone': '+1 (555) 000-0000', 'field-number': '0', 'field-website': 'https://',
    'field-dropdown': 'Select an option',
};

export function hasPlaceholder(type) {
    return !!FIELD_DEFAULT_PLACEHOLDER[type];
}

export function hasOptions(type) {
    return !!DEFAULT_OPTIONS[type];
}

export function canMapToContact(type) {
    return type.startsWith('field-') && !['field-name', 'field-hidden', 'field-checkbox', 'field-consent'].includes(type);
}

// "field-*" only - deliberately excludes 'submit-button', which lives in
// FIELD_PALETTE_ITEMS purely for palette-grouping (it sits visually next to
// the fields) but is a content/control block, not a data-collecting field.
// Matches the same prefix convention FormRenderer.php and
// FormSubmitController::collectFieldBlocks() already use server-side.
export function isFieldBlock(type) {
    return typeof type === 'string' && type.startsWith('field-');
}

// ── Style box model (identical shape to EmailEditor's, so field blocks
// blend visually with content blocks and share the same settings UI) ──────
export function defaultStyles(type) {
    const base = {
        paddingTop: 12, paddingRight: 0, paddingBottom: 12, paddingLeft: 0,
        marginTop: 0, marginRight: 0, marginBottom: 0, marginLeft: 0,
        fontSize: 14, lineHeight: 1.6, color: '#374151', textAlign: 'left',
        blockAlign: 'left', width: 100,
        bgColor: '', bgImageUrl: '',
        borderRadius: 6,
        borderWidth: 0, borderColor: '#e5e7eb', borderAllSides: true,
    };
    const overrides = {
        heading: { paddingTop: 16, paddingBottom: 8, fontSize: 24, lineHeight: 1.3, color: '#111827', textAlign: 'left', fontWeight: 700, borderRadius: 0 },
        text: { borderRadius: 0 },
        button: { paddingTop: 14, paddingBottom: 14, paddingLeft: 24, paddingRight: 24, fontSize: 15, textAlign: 'center', blockAlign: 'center', backgroundColor: '#374151', textColor: '#ffffff', borderRadius: 6 },
        divider: { paddingTop: 4, paddingBottom: 4, borderColor: '#e5e7eb', borderWidth: 0, borderStyle: 'solid', dividerThickness: 1, borderRadius: 0 },
        spacer: { paddingTop: 0, paddingBottom: 0, height: 15 },
        image: { paddingTop: 8, paddingBottom: 8, textAlign: 'center', width: 100, borderRadius: 8 },
        logo: { paddingTop: 8, paddingBottom: 8, blockAlign: 'center', textAlign: 'center', width: 50, fontFamily: 'sans-serif', fontWeight: 'bold', fontSize: 22, color: '#111827', borderRadius: 0 },
        'submit-button': { paddingTop: 14, paddingBottom: 14, fontSize: 15, textAlign: 'center', blockAlign: 'center', backgroundColor: '#4285F4', textColor: '#ffffff', borderRadius: 8, width: 100 },
        'field-hidden': { paddingTop: 0, paddingBottom: 0 },
    };
    return { ...base, ...(overrides[type] ?? {}) };
}

export function makeBlock(paletteItem) {
    const type = paletteItem.type;
    const isField = isFieldBlock(type);

    const base = {
        id: crypto.randomUUID(),
        type,
        styles: defaultStyles(type),
    };

    if (isField) {
        Object.assign(base, {
            label: FIELD_DEFAULT_LABEL[type] || 'Field',
            placeholder: FIELD_DEFAULT_PLACEHOLDER[type] || '',
            help: '',
            required: type === 'field-email',
            options: (DEFAULT_OPTIONS[type] || []).slice(),
            contact_field: DEFAULT_CONTACT_FIELD[type] || null,
            value: '',
            displayAs: type === 'field-radio' ? 'list' : undefined,
        });
        return base;
    }

    const contentDefaults = {
        text: { content: 'Add a short description here. Click to edit.' },
        heading: { content: 'Your Headline Here' },
        image: { src: '', alt: '', link: '' },
        button: { text: 'Learn More', href: '#' },
        divider: {},
        spacer: {},
        column: { columnCount: 2, columns: [{ id: crypto.randomUUID(), blocks: [] }, { id: crypto.randomUUID(), blocks: [] }] },
        html: { html: '' },
        logo: { logoType: 'text', src: '', alt: 'Logo', link: '', brandText: 'Your Brand' },
        'submit-button': { text: 'Subscribe' },
    };
    return { ...base, ...(contentDefaults[type] || {}) };
}

const KNOWN_TYPES = new Set(['body', ...PALETTE_ITEMS.map((p) => p.type), 'column']);

// True when the stored `fields` value is the OLD flat field-array shape
// (from the pre-block-editor builder) rather than a block tree - used to
// decide whether to reset to the default starter template on load, same
// non-destructive pattern EmailEditor.vue uses for isOldDefaultBlocks().
export function isLegacyFieldShape(blocks) {
    if (!Array.isArray(blocks) || blocks.length === 0) return false;
    return blocks.some((b) => {
        if (!b || !KNOWN_TYPES.has(b.type)) return true;
        // The synthetic 'body' block is a flat canvas-settings object and
        // never has a `styles` key by design - every other block type does.
        if (b.type === 'body') return false;
        return !b.styles;
    });
}

export function ensureBlockIds(b) {
    const rb = reactive({ ...b });
    if (!rb.id) rb.id = crypto.randomUUID();
    if (!rb.styles) rb.styles = defaultStyles(rb.type);
    // Repairs submit-button blocks saved by a since-fixed bug where
    // isFieldBlock() wrongly matched 'submit-button', so makeBlock() gave it
    // field properties (label/placeholder/options/...) instead of `text`.
    if (rb.type === 'submit-button' && !rb.text) {
        rb.text = rb.label && rb.label !== 'Field' ? rb.label : 'Subscribe';
        delete rb.label;
        delete rb.placeholder;
        delete rb.help;
        delete rb.options;
        delete rb.contact_field;
        delete rb.value;
    }
    if (rb.type === 'column' && rb.columns) {
        rb.columns.forEach((col) => {
            if (!col.id) col.id = crypto.randomUUID();
            col.blocks = (col.blocks || []).map((sub) => ensureBlockIds(sub));
        });
    }
    return rb;
}

export function blockTypeLabel(type) {
    const contentLabels = { text: 'Text', heading: 'Title', image: 'Image', button: 'Link Button', divider: 'Divider', spacer: 'Spacer', column: 'Columns', html: 'HTML', logo: 'Logo', 'submit-button': 'Submit Button' };
    return contentLabels[type] || FIELD_DEFAULT_LABEL[type] || type;
}

export function splitLines(content) {
    return (content || '').split('\n').map((l) => l.trim()).filter(Boolean);
}

// ── Shared CSS-object builders (identical model to EmailEditor's) ─────────
export function blockContentStyle(block) {
    const s = block.styles || defaultStyles(block.type);
    const style = {
        padding: `${s.paddingTop ?? 12}px ${s.paddingRight ?? 0}px ${s.paddingBottom ?? 12}px ${s.paddingLeft ?? 0}px`,
    };
    if (s.bgColor) style.backgroundColor = s.bgColor;
    if (s.bgImageUrl) { style.backgroundImage = `url(${s.bgImageUrl})`; style.backgroundSize = 'cover'; }
    if (s.borderRadius) style.borderRadius = s.borderRadius + 'px';
    if (s.borderWidth) style.border = `${s.borderWidth}px solid ${s.borderColor || '#e5e7eb'}`;
    if (s.width && s.width !== 'auto' && !['button', 'submit-button', 'logo'].includes(block.type)) {
        const wVal = parseInt(s.width);
        if (wVal < 100) {
            style.width = wVal + '%';
            const align = s.blockAlign || s.textAlign || 'left';
            if (align === 'center') { style.marginLeft = 'auto'; style.marginRight = 'auto'; }
            else if (align === 'right') { style.marginLeft = 'auto'; style.marginRight = '0'; }
            else { style.marginLeft = '0'; style.marginRight = 'auto'; }
        } else {
            style.width = '100%';
        }
    }
    return style;
}

export function textStyle(block) {
    const s = block.styles || defaultStyles(block.type);
    return {
        fontFamily: s.fontFamily || 'inherit',
        fontSize: (s.fontSize || 14) + 'px',
        lineHeight: s.lineHeight || 1.6,
        color: s.color || '#374151',
        textAlign: s.textAlign || 'left',
    };
}

export function headingStyle(block) {
    const s = block.styles || defaultStyles(block.type);
    return {
        ...textStyle(block),
        fontWeight: s.fontWeight || 700,
        fontSize: (s.fontSize || 24) + 'px',
    };
}

export function fieldInputStyle(block) {
    const s = block.styles || defaultStyles(block.type);
    return {
        borderRadius: (s.borderRadius ?? 6) + 'px',
    };
}
