import { beforeEach, describe, expect, it, vi } from 'vitest';

vi.mock('../../../../shared/state', async () => {
  const navigate = vi.fn();
  const setState = vi.fn();
  const sendMessage = vi.fn();
  const getState = vi.fn(() => ({
    view: 'add', entries: [], selectedId: null, selectedItem: null, selectedIndex: 0,
    searchQuery: '', activeGroup: null, error: null, loading: false,
    capturedTabId: null, capturedUrl: '', newType: 'login',
    vaultSettings: null, generatorDefaults: null,
  }));
  const escapeHtml = (s: string) => s
    .replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;')
    .replace(/"/g, '&quot;').replace(/'/g, '&#39;');
  return { navigate, setState, sendMessage, getState, escapeHtml, popOutToTab: vi.fn(), isInTab: vi.fn(() => false), openVaultTab: vi.fn() };
});

import { renderForm } from '../login';
import { sendMessage } from '../../../../shared/state';

describe('Login form packs sectionsDraft into Item.sections', () => {
  beforeEach(() => {
    document.body.innerHTML = '<div id="app"></div>';
    vi.mocked(sendMessage).mockReset();
    vi.mocked(sendMessage).mockResolvedValue({ ok: true, data: { id: 'fakeid0000000000', items: [] } });
  });

  it('persists added sections and fields', async () => {
    const app = document.getElementById('app')!;
    renderForm(app, 'add', null);

    (document.getElementById('f-title') as HTMLInputElement).value = 'Example';

    (document.querySelector('.disclosure__toggle') as HTMLButtonElement).click();
    (document.querySelector('.add-section') as HTMLButtonElement).click();
    (document.querySelector('[data-add-field="text"]') as HTMLButtonElement).click();

    const labelInput = document.querySelector('[data-field-label]') as HTMLInputElement;
    labelInput.value = 'recovery email';
    labelInput.dispatchEvent(new Event('input', { bubbles: true }));
    const valueInput = document.querySelector('[data-field-value-input]') as HTMLInputElement;
    valueInput.value = 'backup@example.com';
    valueInput.dispatchEvent(new Event('input', { bubbles: true }));

    document.getElementById('save-btn')!.click();
    await new Promise((r) => setTimeout(r, 5));

    const calls = vi.mocked(sendMessage).mock.calls;
    const addCall = calls.find(([msg]) => (msg as { type: string }).type === 'add_item');
    const msg = addCall![0] as { type: 'add_item'; item: any };
    expect(msg.item.sections).toHaveLength(1);
    expect(msg.item.sections[0].fields).toHaveLength(1);
    expect(msg.item.sections[0].fields[0].label).toBe('recovery email');
    expect(msg.item.sections[0].fields[0].value).toEqual({ kind: 'text', value: 'backup@example.com' });
    expect(msg.item.sections[0].fields[0].id).toMatch(/^[0-9a-f]{16}$/);
  });
});
