// @vitest-environment happy-dom
import { afterEach, expect, it, vi } from 'vitest';
import { mountEditor as mount } from './helpers/mount';
import { nextTick } from 'vue';
import ColorPicker from '../src/components/ColorPicker.vue';
import MergeTagInput from '../src/components/MergeTagInput.vue';
import ImageField from '../src/components/toolbar/fields/ImageField.vue';
import { attachEditorControls, installControlsStyles } from '../../../../../../resources/assets/js/newsletter-editor/controls.mjs';

let used: string[] = [];
const handlers: Array<() => void> = [];
function bridge() {
    const listener = (event: Event) => {
        const detail = (event as CustomEvent).detail;
        if (detail.value) used.push(detail.value);
        detail.colors = ['#aabbcc', '#112233'];
        detail.recentLabel = 'Senast använda färger'; detail.useLabel = 'Använd färg';
    };
    document.addEventListener('nuhet-color-history', listener);
    handlers.push(() => document.removeEventListener('nuhet-color-history', listener));
}
afterEach(() => { handlers.splice(0).forEach(stop => stop()); used = []; document.body.innerHTML = ''; });

it('common color picker shows attached recent native buttons, shares updates and preserves clear', async () => {
    bridge();
    const first = mount(ColorPicker, { props: { modelValue: '#ffffff' }, attachTo: document.body });
    const second = mount(ColorPicker, { props: { modelValue: '#000000' }, attachTo: document.body });
    handlers.push(() => first.unmount(), () => second.unmount());
    await nextTick();
    expect(used).toEqual([]);
    const group = first.get('[data-ne-recent-colors]');
    expect(group.attributes('aria-label')).toBe('Senast använda färger');
    const button = group.findAll('button')[0];
    expect(button.attributes('type')).toBe('button');
    expect(button.attributes('aria-label')).toBe('Använd färg #aabbcc');
    expect(button.attributes('tabindex')).not.toBe('-1');
    await button.trigger('click');
    expect(first.emitted('update:modelValue')?.at(-1)).toEqual(['#aabbcc']);
    expect(used).toEqual(['#aabbcc']);
    document.dispatchEvent(new CustomEvent('nuhet-recent-colors', { detail: ['#ffee00'] }));
    await nextTick();
    expect(second.get('[data-ne-recent-colors] button').attributes('title')).toBe('#ffee00');
    await first.get('button[aria-label="colorPicker.clear"]').trigger('click');
    expect(first.emitted('update:modelValue')?.at(-1)).toEqual(['']);
    expect(used).toEqual(['#aabbcc']);
});

it('typing does not collect partial colors; change is explicit use and required clear stays unavailable', async () => {
    bridge();
    const picker = mount(ColorPicker, { props: { modelValue: '#ffffff', allowClear: false }, attachTo: document.body });
    handlers.push(() => picker.unmount());
    await nextTick();
    const field = picker.get('input[type="text"]');
    (field.element as HTMLInputElement).value = '#abc'; await field.trigger('input');
    expect(used).toEqual([]);
    await field.trigger('change'); expect(used).toEqual(['#abc']);
    expect(picker.find('button[aria-label="colorPicker.clear"]').exists()).toBe(false);
});

it('programmatic URL changes invalidate a warning and non-URL native fields stay unmarked', async () => {
    const field = mount(MergeTagInput, { props: { modelValue: 'https://old.example.com', type: 'url' }, attachTo: document.body });
    handlers.push(() => field.unmount());
    const input = field.get('input'); const listener = () => used.push('changed');
    input.element.addEventListener('nuhet-url-value', listener);
    expect(input.attributes()).toHaveProperty('data-ne-url');
    await field.setProps({ modelValue: 'https://new.example.com' });
    expect(used).toEqual(['changed']);
    await field.setProps({ type: 'text' }); expect(input.attributes()).not.toHaveProperty('data-ne-url');
});

it('editable custom image URL field is marked, emits user edits and invalidates stale status on media updates', async () => {
    const field = mount(ImageField, { props: { field: { type: 'image', label: 'Image URL' },
        modelValue: 'https://old.example.com/image.png', readOnly: false }, attachTo: document.body });
    handlers.push(() => field.unmount());
    const input = field.get('input[type="url"]');
    expect(input.attributes()).toHaveProperty('data-ne-url');
    expect(input.attributes()).not.toHaveProperty('disabled');
    (input.element as HTMLInputElement).value = 'https://typed.example.com/image.png';
    await input.trigger('input');
    expect(field.emitted('update:modelValue')?.at(-1)).toEqual(['https://typed.example.com/image.png']);
    const listener = () => used.push('image-changed');
    input.element.addEventListener('nuhet-url-value', listener);
    await field.setProps({ modelValue: 'https://media.example.com/new.png' });
    expect((input.element as HTMLInputElement).value).toBe('https://media.example.com/new.png');
    expect(used).toEqual(['image-changed']);
});

function shadowFixture() {
    // These are DOM-only tests: prevent happy-dom from loading the link's asset over the network.
    const settings = (window as any).happyDOM.settings;
    const prior = settings.disableCSSFileLoading; const priorHandling = settings.handleDisabledFileLoadingAsSuccess;
    settings.disableCSSFileLoading = true; settings.handleDisabledFileLoadingAsSuccess = true;
    handlers.push(() => { settings.disableCSSFileLoading = prior; settings.handleDisabledFileLoadingAsSuccess = priorHandling; });
    const host = document.createElement('div'); document.body.append(host);
    const root = host.attachShadow({ mode: 'open' });
    return { host, root, css: new URL('/newsletter-editor/controls.css?id=fixture', document.baseURI).href };
}

it('installs only the dedicated same-site controls sheet once in the actual open root, preserving adopted sheets', () => {
    const { host, root, css } = shadowFixture();
    const sdkSheet = new CSSStyleSheet(); root.adoptedStyleSheets = [sdkSheet];
    const beforeHead = document.head.innerHTML;
    const first = installControlsStyles(host, css);
    expect(first?.getRootNode()).toBe(root);
    expect(installControlsStyles(host, css)).toBe(first);
    expect(root.querySelectorAll('link[data-ne-controls-style]')).toHaveLength(1);
    expect((first as HTMLLinkElement).href).toBe(css);
    expect(document.head.innerHTML).toBe(beforeHead);
    expect(host.querySelector('link')).toBeNull();
    expect(root.querySelector('style')).toBeNull();
    expect(root.adoptedStyleSheets).toEqual([sdkSheet]);
    expect(installControlsStyles(host, 'https://external.example/controls.css')).toBeNull();
    expect(installControlsStyles(host, new URL('/newsletter-editor/workspace.css', document.baseURI).href)).toBeNull();
    expect((first as HTMLLinkElement).href).toBe(css);
});

it('handles shadow-local blur once and cancels a pending check when its actual native panel is removed', async () => {
    vi.useFakeTimers();
    const { host, root, css } = shadowFixture();
    const meta = document.createElement('meta'); meta.name = 'csrf-token'; meta.content = 'fixture-csrf'; document.head.append(meta);
    handlers.push(() => meta.remove());
    const signals: AbortSignal[] = [];
    const request = vi.fn((_url, options) => new Promise((_resolve, reject) => {
        signals.push(options.signal);
        options.signal.addEventListener('abort', () => reject(new DOMException('Aborted', 'AbortError')));
    }));
    const controls = attachEditorControls({ colorContext: [1, 1], context: 'fixture-context',
        urls: { checkUrl: '/newsletter-editor/check-url', controlsCss: css },
        strings: { url_checking: 'Checking', url_warning: 'Warning', url_unavailable: 'Unavailable' },
    }, { document, fetch: request, storage: { getItem: () => null, setItem: () => {} } });
    handlers.push(() => controls.dispose());
    controls.mounted(host); controls.mounted(host);
    const panel = document.createElement('div'); root.append(panel);
    const input = document.createElement('input'); input.type = 'url'; input.dataset.neUrl = ''; input.value = 'https://example.com/'; panel.append(input);
    input.dispatchEvent(new FocusEvent('blur', { composed: true }));
    await vi.advanceTimersByTimeAsync(300);
    expect(request).toHaveBeenCalledTimes(1);
    expect(root.querySelector('.ne-url-status')?.textContent).toBe('Checking');
    panel.remove(); await vi.advanceTimersByTimeAsync(0);
    expect(signals[0].aborted).toBe(true);
    expect(root.querySelector('.ne-url-status')).toBeNull();
    const nextPanel = document.createElement('div'); root.append(nextPanel);
    const next = document.createElement('input'); next.type = 'url'; next.dataset.neUrl = ''; next.value = 'https://other.example.com/'; nextPanel.append(next);
    next.dispatchEvent(new FocusEvent('blur', { composed: false }));
    await vi.advanceTimersByTimeAsync(300);
    expect(request).toHaveBeenCalledTimes(2);
    controls.dispose(); await vi.advanceTimersByTimeAsync(0);
    expect(signals[1].aborted).toBe(true);
    expect(root.querySelector('.ne-url-status')).toBeNull();
    next.dispatchEvent(new FocusEvent('blur', { composed: true }));
    await vi.advanceTimersByTimeAsync(300);
    expect(request).toHaveBeenCalledTimes(2);
});
