import assert from "node:assert/strict";
import { describe, test, mock } from "node:test";
import { act } from "react";
import moment from "moment";
import { deletionAccessError, type DeletionKind, type DeletionSource } from "@/features/shared/deletionAccess";
import { eventStateLabel, eventExternalRegistrationLink } from "@/features/events/eventLifecycle";
import { cardStatusBadges } from "@/features/opportunities/cardStatusBadges";
import { getOpportunityButtonState } from "@/features/shared/opportunityButtonState";
import { useClock } from "@/hooks/useClock";
import { installDom, renderHook } from "./reactHarness";

const at = (value: string) => moment.parseZone(`2026-11-${value}+03:00`);
const source: DeletionSource = { id: 42, created_by: { id: 8 }, start_at: "2026-11-04T16:00:00+03:00", end_at: "2026-11-04T18:00:00+03:00" };

for (const type of ["volunteer", "learnserve", "event"] as DeletionKind[]) describe(`${type}: PDF pages 13/40 deletion phases`, () => {
  const direct = { id: "42", type, requestOnly: false, userId: 8, source };
  test("direct deletion closes exactly 24 hours before the actual session", () => {
    assert.equal(deletionAccessError(direct, at("03T15:59:59")), null);
    assert.equal(deletionAccessError(direct, at("03T16:00:00")), null);
    assert.equal(deletionAccessError(direct, at("03T16:00:01")), "COMMON.EDIT_WINDOW_CLOSED");
  });
  test("a review request occupies only the cutoff-to-start window", () => {
    const review = { ...direct, requestOnly: true };
    assert.equal(deletionAccessError(review, at("03T16:00:00")), "COMMON.DELETION_REVIEW_WINDOW_CLOSED");
    assert.equal(deletionAccessError(review, at("03T16:00:01")), null);
    assert.equal(deletionAccessError(review, at("04T15:59:59")), null);
    for (const now of [at("04T16:00:00"), at("05T12:00:00")]) assert.equal(deletionAccessError(review, now), "COMMON.DELETION_REVIEW_WINDOW_CLOSED");
  });
  test("missing source/clock and another account/record cannot pass", () => {
    for (const change of [{ source: undefined }, { source: { id: 42, is_creator: true } }, { userId: null }, { userId: 9 }, { id: "43" }]) {
      assert.equal(deletionAccessError({ ...direct, ...change }, at("02T12:00:00")), "COMMON.PUBLISH_SOURCE_UNAVAILABLE");
    }
  });
  test("canonical ownership flags work; pending/cancelled remain terminal", () => {
    assert.equal(deletionAccessError({ ...direct, source: { ...source, created_by: null, relationship_tags: ["organizer"] } }, at("02T12:00:00")), null);
    assert.equal(deletionAccessError({ ...direct, source: { ...source, deletion_status: "pending" } }, at("02T12:00:00")), "COMMON.DELETION_ALREADY_PENDING");
    assert.equal(deletionAccessError({ ...direct, source: { ...source, opportunity_status: "cancelled", event_status: "cancelled" } }, at("02T12:00:00")), "COMMON.CANCELLED");
  });
});

test("development with historical or current payments uses administration, including refund-all", () => {
  for (const flag of ["has_successful_payments", "has_active_payments"] as const) for (const requestOnly of [false, true]) {
    assert.equal(deletionAccessError({ id: "42", type: "learnserve", requestOnly, userId: 8, source: { ...source, [flag]: true } }, at("03T17:00:00")), "COMMON.CANCELLATION_CONTACT_ADMIN");
  }
});

describe("PDF pages 3/13/22: event lifecycle follows the actual Kuwait schedule", () => {
  test("upcoming/started/ended changes even when the stored state is stale", () => {
    const event = { ...source, event_status: "upcoming" };
    assert.equal(eventStateLabel(event, at("04T15:59:59")), null);
    assert.equal(eventStateLabel(event, at("04T16:00:00")), "COMMON.STARTED");
    assert.equal(eventStateLabel(event, at("04T18:00:00")), "COMMON.ENDED");
    assert.equal(eventStateLabel({ ...event, event_status: "completed" }, at("03T12:00:00")), null);
  });
  test("cancelled wins over an elapsed schedule; missing dates use the server state", () => {
    assert.equal(eventStateLabel({ ...source, event_status: "cancelled" }, at("05T12:00:00")), "COMMON.CANCELLED");
    assert.equal(eventStateLabel({ event_status: "completed" }, at("05T12:00:00")), "COMMON.ENDED");
    assert.equal(eventStateLabel({ event_status: "inprogress" }, at("05T12:00:00")), "COMMON.STARTED");
  });
  test("optional times use Kuwait calendar days, independently of browser timezone", () => {
    const event = { start_date: "2026-11-04", end_date: "2026-11-04", start_time: null, end_time: null };
    assert.equal(eventStateLabel(event, at("03T23:59:59")), null);
    assert.equal(eventStateLabel(event, at("04T00:00:00")), "COMMON.STARTED");
    assert.equal(eventStateLabel(event, at("05T00:00:00")), "COMMON.ENDED");
  });
});

test("one card clock advances Registered → Participant → Ended without inventing absence", () => {
  const item = { ...source, relationship_tags: [] as [], is_registered: true };
  const labels = (now: moment.Moment) => cardStatusBadges(item, "viewer", false, true, now).map(b => b.label);
  assert.ok(labels(at("04T15:59:59")).includes("COMMON.CARD_REGISTERED_PAID"));
  assert.ok(labels(at("04T16:00:00")).includes("COMMON.PROFILE_BADGE_PARTICIPANT"));
  const ended = labels(at("04T18:00:00"));
  assert.ok(ended.includes("COMMON.ENDED"));
  assert.ok(!ended.includes("COMMON.PROFILE_BADGE_ABSENT"));
  assert.equal(getOpportunityButtonState(item, at("04T18:00:00")), "ended");
  const cancelled = cardStatusBadges({ ...item, opportunity_status: "cancelled" }, "viewer", false, true, at("05T12:00:00")).map(b => b.label);
  assert.deepEqual(cancelled, ["COMMON.CANCELLED"]);
});

test("the real clock hook shares ticks and resumes with fresh time after all cards unmount", () => {
  installDom();
  let now = 1_800_000_000_000;
  const ticks = new Map<number, () => void>();
  let nextTimer = 0;
  mock.method(Date, "now", () => now);
  mock.method(globalThis, "setInterval", (callback: () => void) => { ticks.set(++nextTimer, callback); return nextTimer; });
  mock.method(globalThis, "clearInterval", (timer: number) => { ticks.delete(timer); });
  const first = renderHook(() => useClock(999_983));
  const second = renderHook(() => useClock(999_983));
  try {
    first.mount(); second.mount();
    assert.equal(ticks.size, 1);
    now += 1000;
    act(() => { for (const tick of ticks.values()) tick(); });
    assert.equal(first.last(), now); assert.equal(second.last(), now);
    first.unmount(); assert.equal(ticks.size, 1);
    second.unmount(); assert.equal(ticks.size, 0);
    now += 86_400_000;
    first.mount();
    assert.equal(first.last(), now, "old edit/registration state is never restored after remount");
  } finally { first.unmount(); second.unmount(); mock.restoreAll(); }
});

test("existing deletion URLs carry an explicit direct/review intent without a live request", async () => {
  const { default: apiClient } = await import("@/lib/api/client");
  const { requestEventDeletion } = await import("@/features/events/services/eventsApi");
  const { requestOpportunityDeletion } = await import("@/features/opportunities/services/opportunities");
  const calls: Array<{ url: string; body: unknown }> = [];
  const stub = mock.method(apiClient, "post", async (url: string, body: unknown) => { calls.push({ url, body }); return { data: { key: "success", data: null } }; });
  try {
    await requestEventDeletion("42");
    await requestEventDeletion("42", { requestOnly: true, reason: "Please review" });
    await requestOpportunityDeletion({ id: "42", type: "learnserve", requestOnly: true, reason: "Please review" });
    assert.deepEqual(calls, [
      { url: "/events/42/request-deletion/", body: { request_only: false, reason: undefined } },
      { url: "/events/42/request-deletion/", body: { request_only: true, reason: "Please review" } },
      { url: "/opportunities/42/request-deletion/", body: { type: "learnserve", request_only: true, reason: "Please review" } },
    ]);
  } finally { stub.mock.restore(); }
});


test("event advertising ignores retired internal registration gates and clears a no-registration URL", () => {
  const url = "https://example.org/register";
  assert.equal(eventExternalRegistrationLink({ participation_type_display: { value_en: "Free Event" }, registration_link: url }), null);
  for (const mode of ["Paid Event", "Free Event (Registration Required)"]) assert.equal(eventExternalRegistrationLink({ participation_type_display: { value_en: mode }, registration_link: ` ${url} ` }), url);
  assert.equal(eventExternalRegistrationLink({ registration_link: "  " }), null);
});
