import { describe, it, expect, vi, beforeEach } from 'vitest';
import { wireNotesMonoToggle } from '../notes-tools';

describe('wireNotesMonoToggle', () => {
  let form: HTMLElement;
  let storage: { get: ReturnType<typeof vi.fn>; set: ReturnType<typeof vi.fn> };

  beforeEach(() => {
    form = document.createElement('div');
    form.innerHTML = `
      <button id="notes-mono-btn" class="glyph-btn" type="button" title="monospace">≡</button>
      <textarea id="f-notes"></textarea>
    `;
    document.body.appendChild(form);
    storage = {
      get: vi.fn().mockImplementation((_keys, cb) => cb({})),
      set: vi.fn().mockImplementation((_obj, cb) => cb && cb()),
    };
    (globalThis as any).chrome = { storage: { local: storage } };
  });

  it('toggles class on click and persists', async () => {
    await wireNotesMonoToggle(form, { itemId: 'abc123' });
    const btn = form.querySelector('#notes-mono-btn') as HTMLButtonElement;
    const ta = form.querySelector('#f-notes') as HTMLTextAreaElement;
    expect(ta.classList.contains('f-notes--mono')).toBe(false);
    btn.click();
    expect(ta.classList.contains('f-notes--mono')).toBe(true);
    expect(storage.set).toHaveBeenCalledWith({ 'notesMono.abc123': true }, expect.any(Function));
  });

  it('restores prior state on mount', async () => {
    storage.get.mockImplementation((_keys, cb) => cb({ 'notesMono.abc123': true }));
    await wireNotesMonoToggle(form, { itemId: 'abc123' });
    const ta = form.querySelector('#f-notes') as HTMLTextAreaElement;
    expect(ta.classList.contains('f-notes--mono')).toBe(true);
  });
});
