/**
 * Contract mock of the announcements API (enabled with NEXT_PUBLIC_ANNOUNCEMENTS_MOCK=true).
 *
 * It plays the backend's role end to end so the section can be built and reviewed before
 * /api/admin/announcements/* exists: CRUD and lifecycle with the backend's rules (422 field
 * errors, locked fields after the first publish, rounds), audience counts and eligibility on a
 * fake Fleet population, statistics that grow with time, history. State is kept in
 * localStorage so drafts survive a reload. Never enabled in production.
 */
import type {
  Announcement,
  AnnouncementAudience,
  AnnouncementCatalogs,
  AnnouncementCounts,
  AnnouncementFormat,
  AnnouncementHistoryAction,
  AnnouncementHistoryEntry,
  AnnouncementInput,
  AnnouncementPreviewToken,
  AnnouncementRules,
  AnnouncementStats,
  AnnouncementStatus,
  AudienceCount,
  EligibilityResult,
  MenuLabelEntry,
  MenuLabelSection,
} from "@/domain/entities/announcement";
import type { AnnouncementRepository } from "@/domain/repositories/announcement.repository";
import type { BackendPaginatedData, PaginationQueryParams } from "@/shared/types";
import { env } from "@/infrastructure/config/env";
import { messagesFr } from "@/shared/i18n/messages-fr";
import { NEW_USER_MAX_DAYS } from "@/shared/constants/announcements";
import {
  displayState,
  issuesToFieldErrors,
  validateAnnouncement,
  type ValidationIssue,
} from "@/shared/lib/announcements";
import {
  DAY,
  MOCK_CATALOGS,
  MOCK_COMPANIES,
  MOCK_EXAMPLE_VEHICLES,
  MOCK_POPULATION,
  seedAnnouncements,
  seedHistory,
  type MockCompany,
  type MockUser,
} from "@/infrastructure/repositories/announcement.mock-data";

const STORAGE_KEY = "dadycar-admin:announcements-mock:v1";
const ME = "Vous (démo)";
const m = messagesFr.announcements;

const sleep = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms));
const clone = <T,>(value: T): T => structuredClone(value);

interface RoundMeta {
  n: number;
  started_at: string;
  ended_at: string | null;
}

type Stored = Omit<Announcement, "counts"> & { rounds: RoundMeta[] };

interface State {
  items: Stored[];
  history: Record<number, AnnouncementHistoryEntry[]>;
  seq: number;
  historySeq: number;
}

/** An axios-shaped error, so the screens handle the mock and the API the same way. */
function apiError(status: number, message: string, errors?: Record<string, string[]>) {
  return Object.assign(new Error(message), { response: { status, data: { status: false, message, errors } } });
}

function issueMessage(issue: ValidationIssue): string {
  const v = m.validation;
  switch (issue.code) {
    case "tooLong": return v.tooLong(issue.max ?? 0);
    case "stepsMin": return v.stepsMin(issue.min ?? 0);
    case "stepsMax": return v.stepsMax(issue.max ?? 0);
    default: return v[issue.code];
  }
}

function invalid(issues: ValidationIssue[]) {
  return apiError(422, m.toasts.fixErrors, issuesToFieldErrors(issues, issueMessage));
}

// ── Audience matching on the fake population ─────────────────────────────────

const companyById = new Map<number, MockCompany>(MOCK_COMPANIES.map((c) => [c.id, c]));

type Miss = "plan" | "capabilityMissing" | "capabilityPresent" | "notIncluded" | "excluded" | "permission" | "role" | "language" | "accountAge";

/** Why a user is left out (first failing rule), or null when the user matches. */
function miss(user: MockUser, a: AnnouncementAudience, rules?: AnnouncementRules): { kind: Miss; detail?: string } | null {
  const company = companyById.get(user.company_id)!;
  if (a.companies_include.length && !a.companies_include.includes(company.id)) return { kind: "notIncluded" };
  if (a.companies_exclude.includes(company.id)) return { kind: "excluded" };
  if (a.plans.length && !a.plans.includes(company.plan)) return { kind: "plan", detail: company.plan };
  const lacking = a.capabilities_required.find((c) => !company.capabilities.includes(c));
  if (lacking) return { kind: "capabilityMissing", detail: lacking };
  const owned = a.capabilities_missing.find((c) => company.capabilities.includes(c));
  if (owned) return { kind: "capabilityPresent", detail: owned };
  if (a.permissions.some((p) => !user.permissions.includes(p))) return { kind: "permission" };
  if (a.roles.length && !a.roles.includes(user.role)) return { kind: "role" };
  if (a.languages.length && !a.languages.includes(user.language)) return { kind: "language" };
  const min = rules?.account_age_min_days ?? null;
  const max = a.new_users_only ? Math.min(rules?.account_age_max_days ?? NEW_USER_MAX_DAYS, NEW_USER_MAX_DAYS) : rules?.account_age_max_days ?? null;
  if ((min !== null && user.account_age_days < min) || (max !== null && user.account_age_days > max)) return { kind: "accountAge" };
  return null;
}

function countAudience(a: AnnouncementAudience, rules?: AnnouncementRules): number {
  let n = 0;
  for (const user of MOCK_POPULATION) if (!miss(user, a, rules)) n++;
  return n;
}

const label = (options: { value: string; label: string }[], value: string) =>
  options.find((o) => o.value === value)?.label ?? value;

// ── Statistics that grow with time ───────────────────────────────────────────

const RATES: Record<AnnouncementFormat, { seen: number; click: number; complete: number; dismiss: number }> = {
  badge: { seen: 0.55, click: 0.25, complete: 0, dismiss: 0 },
  sidebar_spotlight: { seen: 0.7, click: 0.3, complete: 0, dismiss: 0.2 },
  banner: { seen: 0.8, click: 0.12, complete: 0, dismiss: 0.3 },
  modal: { seen: 0.92, click: 0.35, complete: 0, dismiss: 0.4 },
  page_widget: { seen: 0.75, click: 0.4, complete: 0.5, dismiss: 0.25 },
  tour: { seen: 0.7, click: 0.45, complete: 0.6, dismiss: 0.2 },
};

const jitter = (id: number, salt: number) => 0.85 + (((id * 2654435761 + salt * 97) >>> 0) % 30) / 100;

/** Days the announcement was shown during one round. */
function exposureDays(a: Stored, round: RoundMeta, now: number): number {
  const start = Math.max(new Date(round.started_at).getTime(), a.starts_at ? new Date(a.starts_at).getTime() : 0);
  const end = Math.min(round.ended_at ? new Date(round.ended_at).getTime() : now, a.ends_at ? new Date(a.ends_at).getTime() : now, now);
  return Math.max(0, (end - start) / DAY);
}

function roundCounts(a: Stored, round: RoundMeta, eligible: number, now: number): AnnouncementCounts {
  const r = RATES[a.format];
  const progress = 1 - Math.exp(-exposureDays(a, round, now) / 5);
  const seen = Math.round(eligible * r.seen * progress * jitter(a.id, round.n));
  const clicked = Math.round(seen * r.click * jitter(a.id, round.n + 7));
  const completed = r.complete ? Math.round(seen * r.complete * jitter(a.id, round.n + 3)) : clicked;
  const dismissed = Math.round(seen * r.dismiss * jitter(a.id, round.n + 5));
  return { eligible, seen, clicked, dismissed, completed };
}

const zeroCounts = (eligible: number): AnnouncementCounts => ({ eligible, seen: 0, clicked: 0, dismissed: 0, completed: 0 });

function sumCounts(list: AnnouncementCounts[], eligible: number): AnnouncementCounts {
  return list.reduce(
    (acc, c) => ({ eligible, seen: acc.seen + c.seen, clicked: acc.clicked + c.clicked, dismissed: acc.dismissed + c.dismissed, completed: acc.completed + c.completed }),
    zeroCounts(eligible),
  );
}

// ── The mock ─────────────────────────────────────────────────────────────────

export class AnnouncementRepositoryMock implements AnnouncementRepository {
  private state: State | null = null;

  private load(): State {
    if (this.state) return this.state;
    try {
      const raw = typeof window !== "undefined" ? window.localStorage.getItem(STORAGE_KEY) : null;
      if (raw) {
        this.state = JSON.parse(raw) as State;
        return this.state;
      }
    } catch {
      // Unreadable storage: start from the seeds.
    }
    this.state = this.seed();
    this.save();
    return this.state;
  }

  private save() {
    try {
      if (typeof window !== "undefined" && this.state) window.localStorage.setItem(STORAGE_KEY, JSON.stringify(this.state));
    } catch {
      // Storage full (large images) or blocked: the session keeps working in memory.
    }
  }

  private seed(): State {
    const now = Date.now();
    const { seeds } = seedAnnouncements(now);
    const iso = (daysAgo: number) => new Date(now - daysAgo * DAY).toISOString();
    const items: Stored[] = seeds.map((s) => {
      const { created_days_ago, published_days_ago, round_started_days_ago, ...rest } = s;
      const rounds: RoundMeta[] = [];
      if (published_days_ago !== null) {
        if (s.round > 1 && round_started_days_ago !== null) {
          rounds.push({ n: 1, started_at: iso(published_days_ago), ended_at: iso(round_started_days_ago) });
          rounds.push({ n: 2, started_at: iso(round_started_days_ago), ended_at: null });
        } else {
          rounds.push({ n: 1, started_at: iso(published_days_ago), ended_at: s.status === "archived" ? iso(55) : null });
        }
      }
      return {
        ...rest,
        first_published_at: published_days_ago !== null ? iso(published_days_ago) : null,
        created_at: iso(created_days_ago),
        updated_at: iso(Math.min(created_days_ago, published_days_ago ?? created_days_ago)),
        rounds,
      };
    });
    return { items, history: seedHistory(seeds, now), seq: 100, historySeq: 1000 };
  }

  /** Reset the demo data (exposed for the dev console: `window.__resetAnnouncementsMock()`). */
  resetDemo() {
    this.state = this.seed();
    this.save();
  }

  private find(id: number): Stored {
    const item = this.load().items.find((a) => a.id === id);
    if (!item) throw apiError(404, m.errors.notFound);
    return item;
  }

  private log(id: number, action: AnnouncementHistoryAction, detail: string | null = null) {
    const state = this.load();
    const entry: AnnouncementHistoryEntry = { id: ++state.historySeq, action, by: ME, at: new Date().toISOString(), detail };
    state.history[id] = [entry, ...(state.history[id] ?? [])];
  }

  private view(a: Stored): Announcement {
    const now = Date.now();
    const eligible = countAudience(a.audience, a.rules);
    const current = a.rounds.find((r) => r.n === a.round);
    const counts = current ? roundCounts(a, current, eligible, now) : zeroCounts(eligible);
    // eslint-disable-next-line @typescript-eslint/no-unused-vars
    const { rounds, ...rest } = a;
    return clone({ ...rest, counts });
  }

  private keyTaken(key: string, exceptId?: number) {
    return this.load().items.some((a) => a.key === key && a.id !== exceptId);
  }

  private uniqueKey(base: string) {
    let key = base;
    let i = 2;
    while (this.keyTaken(key)) key = `${base}-${i++}`;
    return key;
  }

  // ── Reads ──────────────────────────────────────────────────────────────────

  async list(params: PaginationQueryParams): Promise<BackendPaginatedData<Announcement>> {
    await sleep(200);
    const now = Date.now();
    let rows = this.load().items.map((a) => this.view(a));

    const search = String(params.search ?? "").trim().toLowerCase();
    if (search) {
      rows = rows.filter((a) => [a.title.fr, a.title.en, a.key].some((v) => v.toLowerCase().includes(search)));
    }
    if (params.state) rows = rows.filter((a) => displayState(a, now) === params.state);
    if (params.format) rows = rows.filter((a) => a.format === params.format);

    const orderBy = String(params.order_by ?? "updated_at");
    const dir = params.order === "ASC" ? 1 : -1;
    const value = (a: Announcement): string | number => {
      switch (orderBy) {
        case "title": return a.title.fr.toLowerCase();
        case "starts_at": return a.starts_at ?? a.first_published_at ?? "";
        case "seen": return a.counts.seen;
        default: return a.updated_at;
      }
    };
    rows.sort((x, y) => (value(x) > value(y) ? dir : value(x) < value(y) ? -dir : 0));

    const perPage = Number(params.per_page ?? 15);
    const page = Number(params.page ?? 1);
    const lastPage = Math.max(1, Math.ceil(rows.length / perPage));
    return {
      total: rows.length,
      count: Math.min(perPage, Math.max(0, rows.length - (page - 1) * perPage)),
      per_page: perPage,
      current_page: page,
      last_page: lastPage,
      previous_page_url: page > 1 ? "mock" : null,
      next_page_url: page < lastPage ? "mock" : null,
      items: rows.slice((page - 1) * perPage, page * perPage),
    };
  }

  async get(id: number): Promise<Announcement> {
    await sleep(150);
    return this.view(this.find(id));
  }

  async history(id: number): Promise<AnnouncementHistoryEntry[]> {
    await sleep(120);
    this.find(id);
    return clone(this.load().history[id] ?? []);
  }

  async stats(id: number, round?: number): Promise<AnnouncementStats> {
    await sleep(250);
    const a = this.find(id);
    const now = Date.now();
    const eligible = countAudience(a.audience, a.rules);
    const all = round === 0;
    const selected = all ? a.rounds : a.rounds.filter((r) => r.n === (round ?? a.round));
    const counts = sumCounts(selected.map((r) => roundCounts(a, r, eligible, now)), eligible);
    const r = RATES[a.format];

    const steps = a.steps.map((s, i) => {
      const seen = Math.round(counts.seen * Math.pow(0.82, i));
      const isLast = i === a.steps.length - 1;
      const completed = isLast ? Math.min(seen, counts.completed) : Math.round(seen * 0.86);
      // The demo step card shows a broken placement on its second step.
      const anchorMissing = s.anchor_key && a.format === "page_widget" && i === 1 ? Math.round(seen * 0.04) : 0;
      return { step_id: s.id, title: s.title.fr || m.steps.step(i + 1), seen, completed, anchor_missing: anchorMissing };
    });
    const anchorMissing = steps.reduce((sum, s) => sum + s.anchor_missing, 0);

    const rateNotSeen = a.success_event ? 0.05 * jitter(a.id, 11) : 0;
    const rateSeen = a.success_event ? Math.min(0.9, rateNotSeen + r.click * 0.7 * jitter(a.id, 13)) : 0;
    const adoptedSeen = Math.round(counts.seen * rateSeen);
    const adoptedNotSeen = Math.round(Math.max(0, counts.eligible - counts.seen) * rateNotSeen);
    const series = Array.from({ length: 14 }, (_, i) => {
      const k = (i + 1) / 14;
      return {
        date: new Date(now - (13 - i) * DAY).toISOString().slice(0, 10),
        rate_seen: Math.round(rateSeen * (1 - Math.exp(-k * 3)) * 1000) / 10,
        rate_not_seen: Math.round(rateNotSeen * (0.6 + 0.4 * k) * 1000) / 10,
      };
    });

    return {
      round: all ? 0 : round ?? a.round,
      rounds: a.rounds.map((x) => x.n),
      counts,
      dismiss_rate: counts.seen ? Math.round((counts.dismissed / counts.seen) * 1000) / 10 : 0,
      steps,
      anchor_missing: anchorMissing,
      adoption: {
        event: a.success_event,
        adopted_after_seen: adoptedSeen,
        adopted_not_seen: adoptedNotSeen,
        rate_seen: Math.round(rateSeen * 1000) / 10,
        rate_not_seen: Math.round(rateNotSeen * 1000) / 10,
        series,
      },
      reminder_targets: a.reminder.enabled && a.success_event ? Math.max(0, counts.seen - adoptedSeen) : 0,
      posthog_url: env.announcementsPosthogUrl || null,
    };
  }

  async audienceCount(audience: AnnouncementAudience, rules?: AnnouncementRules): Promise<AudienceCount> {
    await sleep(180);
    return { count: countAudience(audience, rules), total: MOCK_POPULATION.length };
  }

  async eligibility(input: {
    company_id: number;
    audience: AnnouncementAudience;
    rules: AnnouncementRules;
    starts_at: string | null;
    ends_at: string | null;
    status: AnnouncementStatus;
  }): Promise<EligibilityResult> {
    await sleep(220);
    const users = MOCK_POPULATION.filter((u) => u.company_id === input.company_id);
    const reasons: string[] = [];
    const now = Date.now();
    if (input.status !== "published") reasons.push(m.reasons.notPublished);
    else if ((input.starts_at && new Date(input.starts_at).getTime() > now) || (input.ends_at && new Date(input.ends_at).getTime() < now)) {
      reasons.push(m.reasons.outOfPeriod);
    }

    const tally = new Map<Miss, { n: number; detail?: string }>();
    let matching = 0;
    for (const user of users) {
      const out = miss(user, input.audience, input.rules);
      if (!out) matching++;
      else {
        const t = tally.get(out.kind) ?? { n: 0, detail: out.detail };
        t.n++;
        tally.set(out.kind, t);
      }
    }
    for (const [kind, { n, detail }] of tally) {
      switch (kind) {
        case "plan": reasons.push(m.reasons.plan(label(MOCK_CATALOGS.plans, detail ?? ""))); break;
        case "capabilityMissing": reasons.push(m.reasons.capabilityMissing(label(MOCK_CATALOGS.capabilities, detail ?? ""))); break;
        case "capabilityPresent": reasons.push(m.reasons.capabilityPresent(label(MOCK_CATALOGS.capabilities, detail ?? ""))); break;
        case "notIncluded": reasons.push(m.reasons.notIncluded); break;
        case "excluded": reasons.push(m.reasons.excluded); break;
        case "permission": reasons.push(m.reasons.permission(n)); break;
        case "role": reasons.push(m.reasons.role(n)); break;
        case "language": reasons.push(m.reasons.language(n)); break;
        case "accountAge": reasons.push(m.reasons.accountAge(n)); break;
      }
    }
    const shownNow = input.status === "published" && !reasons.includes(m.reasons.outOfPeriod);
    return { eligible: shownNow && matching > 0, matching_users: matching, company_users: users.length, reasons };
  }

  async overlappingModals(input: { id?: number; starts_at: string | null; ends_at: string | null; audience: AnnouncementAudience }): Promise<Announcement[]> {
    await sleep(150);
    const now = Date.now();
    const start = (v: string | null) => (v ? new Date(v).getTime() : now);
    const end = (v: string | null) => (v ? new Date(v).getTime() : Number.POSITIVE_INFINITY);
    const shares = (a: AnnouncementAudience, b: AnnouncementAudience) =>
      MOCK_POPULATION.some((u) => !miss(u, a) && !miss(u, b));
    return this.load()
      .items.filter((a) => a.id !== input.id && a.format === "modal" && a.status === "published")
      .filter((a) => displayState(a, now) !== "ended")
      .filter((a) => start(a.starts_at) < end(input.ends_at) && start(input.starts_at) < end(a.ends_at))
      .filter((a) => shares(a.audience, input.audience))
      .map((a) => this.view(a));
  }

  async catalogs(): Promise<AnnouncementCatalogs> {
    await sleep(120);
    return clone({ ...MOCK_CATALOGS, companies: MOCK_COMPANIES.map((c) => ({ value: c.id, label: c.name })) });
  }

  async exampleVehicles(search: string) {
    await sleep(120);
    const q = search.trim().toLowerCase().replace(/[\s-]/g, "");
    return MOCK_EXAMPLE_VEHICLES.filter(
      (v) => !q || v.numberplate.toLowerCase().replace(/-/g, "").includes(q) || v.make_model.toLowerCase().includes(q),
    );
  }

  async previewToken(id: number, exampleVehicleId?: number): Promise<AnnouncementPreviewToken> {
    await sleep(200);
    const a = this.find(id);
    const page = MOCK_CATALOGS.pages.find((p) => p.key === a.page_key);
    let path = page?.path ?? (a.target_sidebar_path || "/fleet/dashboard");
    if (path.includes(":id")) path = path.replace(":id", String(exampleVehicleId ?? MOCK_EXAMPLE_VEHICLES[0].id));
    const token = `prev_${Math.random().toString(36).slice(2, 12)}`;
    return {
      token,
      preview_url: `${env.fleetUrl}${path}?announcement_preview=${token}`,
      expires_at: new Date(Date.now() + 30 * 60_000).toISOString(),
    };
  }

  async uploadMedia(file: File): Promise<{ url: string }> {
    await sleep(300);
    // Small images are kept as data URLs so they survive a reload; larger ones live for the session.
    if (file.size <= 600_000) {
      const url = await new Promise<string>((resolve, reject) => {
        const reader = new FileReader();
        reader.onload = () => resolve(String(reader.result));
        reader.onerror = () => reject(reader.error);
        reader.readAsDataURL(file);
      });
      return { url };
    }
    return { url: URL.createObjectURL(file) };
  }

  // ── Writes ─────────────────────────────────────────────────────────────────

  async create(input: AnnouncementInput): Promise<Announcement> {
    await sleep(300);
    const issues = validateAnnouncement(input, "draft");
    if (input.key && this.keyTaken(input.key)) issues.push({ field: "key", code: "keyTaken" });
    if (issues.length) throw invalid(issues);
    const state = this.load();
    const now = new Date().toISOString();
    const item: Stored = {
      ...clone(input),
      id: ++state.seq,
      status: "draft",
      round: 0,
      first_published_at: null,
      created_by: ME,
      created_at: now,
      updated_at: now,
      rounds: [],
    };
    state.items.push(item);
    this.log(item.id, "created");
    this.save();
    return this.view(item);
  }

  async update(id: number, input: AnnouncementInput): Promise<Announcement> {
    await sleep(300);
    const item = this.find(id);
    const issues = validateAnnouncement(input, item.status === "published" ? "publish" : "draft");
    if (input.key && this.keyTaken(input.key, id)) issues.push({ field: "key", code: "keyTaken" });
    if (issues.length) throw invalid(issues);

    if (item.first_published_at) {
      const locked: Record<string, string[]> = {};
      if (input.key !== item.key) locked.key = [m.editor.lockedField];
      if (input.format !== item.format) locked.format = [m.editor.lockedField];
      if (input.steps.map((s) => s.id).join() !== item.steps.map((s) => s.id).join()) locked.steps = [m.steps.countLocked];
      if (Object.keys(locked).length) throw apiError(422, m.toasts.fixErrors, locked);
    }

    const changed = (Object.keys(input) as (keyof AnnouncementInput)[]).filter(
      (k) => JSON.stringify(input[k]) !== JSON.stringify(item[k]),
    );
    const names = m.validation.fieldNames;
    const detail = changed.map((k) => names[String(k).replace(/_(label|path|alt)$/, "")] ?? String(k)).filter((v, i, arr) => arr.indexOf(v) === i).join(", ");

    Object.assign(item, clone(input), { updated_at: new Date().toISOString() });
    if (changed.length) this.log(id, "updated", detail || null);
    this.save();
    return this.view(item);
  }

  async remove(id: number): Promise<void> {
    await sleep(200);
    const item = this.find(id);
    if (item.status !== "draft" || item.first_published_at) throw apiError(422, m.confirm.deleteBody);
    const state = this.load();
    state.items = state.items.filter((a) => a.id !== id);
    delete state.history[id];
    this.save();
  }

  async publish(id: number): Promise<Announcement> {
    await sleep(350);
    const item = this.find(id);
    const issues = validateAnnouncement(item, "publish");
    if (issues.length) throw invalid(issues);
    const now = new Date().toISOString();
    item.status = "published";
    item.first_published_at ??= now;
    if (item.round === 0) item.round = 1;
    const current = item.rounds.find((r) => r.n === item.round);
    if (!current) item.rounds.push({ n: item.round, started_at: now, ended_at: null });
    else current.ended_at = null;
    item.updated_at = now;
    const recipients = item.notify.enabled ? countAudience(item.audience, item.rules) : 0;
    this.log(id, "published", item.notify.enabled ? `Notification envoyée à ${recipients} utilisateurs` : null);
    this.save();
    return this.view(item);
  }

  async unpublish(id: number): Promise<Announcement> {
    await sleep(250);
    const item = this.find(id);
    item.status = "draft";
    const current = item.rounds.find((r) => r.n === item.round);
    if (current) current.ended_at = new Date().toISOString();
    item.updated_at = new Date().toISOString();
    this.log(id, "unpublished");
    this.save();
    return this.view(item);
  }

  async archive(id: number): Promise<Announcement> {
    await sleep(250);
    const item = this.find(id);
    item.status = "archived";
    const current = item.rounds.find((r) => r.n === item.round);
    if (current && !current.ended_at) current.ended_at = new Date().toISOString();
    item.updated_at = new Date().toISOString();
    this.log(id, "archived");
    this.save();
    return this.view(item);
  }

  async duplicate(id: number): Promise<Announcement> {
    await sleep(250);
    const source = this.find(id);
    const state = this.load();
    const now = new Date().toISOString();
    const copy: Stored = {
      ...clone(source),
      id: ++state.seq,
      key: this.uniqueKey(`${source.key}-copie`.slice(0, 60)),
      title: { fr: `${source.title.fr} (copie)`.slice(0, 60), en: source.title.en ? `${source.title.en} (copy)`.slice(0, 60) : "" },
      status: "draft",
      round: 0,
      first_published_at: null,
      created_by: ME,
      created_at: now,
      updated_at: now,
      rounds: [],
    };
    state.items.push(copy);
    this.log(copy.id, "duplicated", source.title.fr);
    this.save();
    return this.view(copy);
  }

  async reset(id: number, reason?: string): Promise<Announcement> {
    await sleep(300);
    const item = this.find(id);
    const now = new Date().toISOString();
    const current = item.rounds.find((r) => r.n === item.round);
    if (current) current.ended_at = now;
    item.round += 1;
    item.rounds.push({ n: item.round, started_at: now, ended_at: null });
    item.updated_at = now;
    this.log(id, "reset", reason?.trim() || null);
    this.save();
    return this.view(item);
  }

  // A few entries of Fleet's menu, kept for the session only.
  private menu: MenuLabelSection[] = [
    { id: 1, label: "Tableau de bord", hint: "Dashboard", items: [
      { id: 1, label: "Tableau de bord", hint: "Dashboard", path: "/fleet/dashboard", shown: false, text: null },
    ] },
    { id: 2, label: "Véhicules", hint: "Vehicles", items: [
      { id: 2, label: "Véhicules", hint: "Vehicles", path: "/fleet/vehicles", shown: false, text: null },
      { id: 3, label: "Secteurs", hint: "Sectors", path: "/fleet/sectors", shown: true, text: null },
    ] },
    { id: 3, label: "Rapports", hint: "Reports", items: [
      { id: 4, label: "Rapports V2", hint: "Reports V2", path: "/fleet/reports-V2", shown: true, text: "V2" },
    ] },
  ];

  async menuLabels(): Promise<MenuLabelSection[]> {
    await sleep(200);
    return structuredClone(this.menu);
  }

  async updateMenuLabel(id: number, input: { shown: boolean; text: string | null }): Promise<MenuLabelEntry> {
    await sleep(200);
    const entry = this.menu.flatMap((s) => s.items).find((e) => e.id === id);
    if (!entry) throw new Error("Entrée du menu introuvable");
    entry.shown = input.shown;
    entry.text = input.text?.trim() || null;
    return { ...entry };
  }
}
