export interface NotesMonoOpts {
  /// Item ID for persistence — pass empty string for "add new" forms (state
  /// is then session-scoped under the key 'notesMono.__new__').
  itemId: string;
}

export async function wireNotesMonoToggle(form: HTMLElement, opts: NotesMonoOpts): Promise<void> {
  const btn = form.querySelector<HTMLButtonElement>('#notes-mono-btn');
  const ta = form.querySelector<HTMLTextAreaElement>('#f-notes');
  if (!btn || !ta) return;

  const key = `notesMono.${opts.itemId || '__new__'}`;

  // chrome.storage may be absent in test environments — guard gracefully.
  if (typeof chrome !== 'undefined' && chrome.storage?.local) {
    const stored = await new Promise<boolean>((resolve) => {
      chrome.storage.local.get([key], (result) => resolve(!!result[key]));
    });
    if (stored) ta.classList.add('f-notes--mono');
  }

  btn.addEventListener('click', () => {
    const next = !ta.classList.contains('f-notes--mono');
    ta.classList.toggle('f-notes--mono', next);
    if (typeof chrome !== 'undefined' && chrome.storage?.local) {
      chrome.storage.local.set({ [key]: next }, () => { /* fire and forget */ });
    }
  });
}
