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: 'secure_note',
  }));
  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 '../secure-note';
import { sendMessage } from '../../../../shared/state';

describe('SecureNote save shape', () => {
  beforeEach(() => {
    document.body.innerHTML = '<div id="app"></div>';
    vi.mocked(sendMessage).mockReset();
    vi.mocked(sendMessage).mockResolvedValue({ ok: true, data: { id: 'fakeid0000000000', items: [] } });
  });

  it('builds an Item with type=secure_note and the body in core', async () => {
    const app = document.getElementById('app')!;
    renderForm(app, 'add', null);

    (document.getElementById('f-title') as HTMLInputElement).value = 'My Secret Note';
    (document.getElementById('f-body') as HTMLTextAreaElement).value = 'hello\nworld';

    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');
    expect(addCall).toBeDefined();
    const msg = addCall![0] as { type: 'add_item'; item: any };
    expect(msg.item.title).toBe('My Secret Note');
    expect(msg.item.type).toBe('secure_note');
    expect(msg.item.core).toEqual({ type: 'secure_note', body: 'hello\nworld' });
    expect(msg.item.trashed_at).toBeUndefined();
    expect(msg.item.sections).toEqual([]);
    expect(msg.item.attachments).toEqual([]);
  });
});
