/**
 * Regression tests for the shared "scroll to the first invalid field" helper.
 *
 * It replaced three copies — one each in `VolunteerForm`, `LearnServeForm` and
 * `EventForm` — that were identical apart from their selector maps. These cover
 * the lookup order and the fallback, which is what a caller depends on and what
 * silently degrades if it changes: the failure mode is a Submit button that
 * looks unresponsive, not an error.
 *
 * There is no DOM in `node --test`, so `document` is stubbed to exactly the
 * three methods the helper calls. That keeps the test honest about what it
 * covers: the lookup *order*, not real scrolling.
 */
import { test, describe, beforeEach, afterEach } from "node:test";
import assert from "node:assert/strict";
import { scrollToFirstError } from "@/features/shared/scrollToFirstError";

interface FakeElement {
  id: string;
  scrolled?: ScrollIntoViewOptions;
}

let byQuery: Record<string, FakeElement>;
let byId: Record<string, FakeElement>;
let queries: string[];

const element = (id: string): FakeElement => {
  const el: FakeElement = { id };
  (el as unknown as Element).scrollIntoView = ((options: ScrollIntoViewOptions) => {
    el.scrolled = options;
  }) as Element["scrollIntoView"];
  return el;
};

beforeEach(() => {
  byQuery = {};
  byId = {};
  queries = [];
  globalThis.document = {
    querySelector: (selector: string) => {
      queries.push(selector);
      return (byQuery[selector] ?? null) as unknown as Element | null;
    },
    getElementById: (id: string) => (byId[id] ?? null) as unknown as HTMLElement | null,
  } as unknown as Document;
});

afterEach(() => {
  delete (globalThis as { document?: unknown }).document;
});

describe("scrollToFirstError", () => {
  test("does nothing when there are no errors", () => {
    scrollToFirstError({});
    scrollToFirstError(undefined);
    scrollToFirstError(null);
    assert.deepEqual(queries, []);
  });

  test("prefers a matching name attribute", () => {
    const target = element("by-name");
    byQuery['[name="title_ar"]'] = target;
    scrollToFirstError({ title_ar: "required" });
    assert.deepEqual(target.scrolled, { behavior: "smooth", block: "center" });
  });

  test("falls back to the caller's selector for fields with no named input", () => {
    // A rich text editor renders no input carrying the field's name, which is
    // the whole reason the selector map exists.
    const target = element("by-selector");
    byQuery[".descritpionitm-ar"] = target;
    scrollToFirstError(
      { description_ar: "required" },
      { description_ar: ".descritpionitm-ar" }
    );
    assert.equal(target.scrolled?.block, "center");
  });

  test("falls back to an element id last", () => {
    const target = element("by-id");
    byId.scheduleDates = target;
    scrollToFirstError({ scheduleDates: "required" });
    assert.equal(target.scrolled?.block, "center");
  });

  test("stops at the first field it can locate", () => {
    const second = element("second");
    byQuery['[name="second"]'] = second;
    // `first` is not present anywhere, so the helper moves on to `second` —
    // and must not keep going past it.
    const third = element("third");
    byQuery['[name="third"]'] = third;

    scrollToFirstError({ first: "e", second: "e", third: "e" });

    assert.ok(second.scrolled, "scrolled to the first locatable field");
    assert.equal(third.scrolled, undefined, "did not continue past it");
  });

  test("scrolls to the top of the form when no field can be located", () => {
    // Otherwise Submit appears to do nothing at all.
    const form = element("form");
    byQuery.form = form;
    scrollToFirstError({ mystery_field: "required" });
    assert.deepEqual(form.scrolled, { behavior: "smooth", block: "start" });
  });

  test("survives a form that is not on the page either", () => {
    assert.doesNotThrow(() => scrollToFirstError({ mystery_field: "required" }));
  });
});
