/**
 * Fixtures of the announcements contract mock: the catalogs the pickers read, a fake Fleet
 * population the audience counts run on, and the seed announcements (every format and state).
 */
import type {
  Announcement,
  AnnouncementCatalogs,
  AnnouncementExampleVehicle,
  AnnouncementHistoryEntry,
  AnnouncementStep,
  LocalizedText,
} from "@/domain/entities/announcement";
import { DEFAULT_AUDIENCE, DEFAULT_NOTIFY, DEFAULT_REMINDER, DEFAULT_RULES } from "@/shared/constants/announcements";

// ── Deterministic random ─────────────────────────────────────────────────────

export function mulberry32(seed: number) {
  let a = seed;
  return () => {
    a |= 0;
    a = (a + 0x6d2b79f5) | 0;
    let t = Math.imul(a ^ (a >>> 15), 1 | a);
    t = (t + Math.imul(t ^ (t >>> 7), 61 | t)) ^ t;
    return ((t ^ (t >>> 14)) >>> 0) / 4294967296;
  };
}

export const DAY = 86_400_000;

const tx = (fr: string, en = ""): LocalizedText => ({ fr, en });

// ── Catalogs ─────────────────────────────────────────────────────────────────

const MENU = [
  { path: "/fleet/dashboard", key: "sidebar.dashboard", label: "Tableau de bord" },
  { path: "/fleet/vehicles", key: "sidebar.vehicles", label: "Véhicules" },
  { path: "/fleet/car-location", key: "sidebar.car-location", label: "Localisation des véhicules" },
  { path: "/fleet/completeness", key: "sidebar.completeness", label: "Complétude du parc" },
  { path: "/fleet/employees", key: "sidebar.employees", label: "Conducteurs" },
  { path: "/fleet/documents", key: "sidebar.documents", label: "Documents" },
  { path: "/fleet/costs", key: "sidebar.costs", label: "Coûts" },
  { path: "/fleet/infractions", key: "sidebar.infractions", label: "Infractions" },
  { path: "/fleet/donna", key: "sidebar.donna", label: "Donna (assistant IA)" },
];

export const MOCK_CATALOGS: Omit<AnnouncementCatalogs, "companies"> = {
  pages: [
    { key: "dashboard", label: "Tableau de bord", path: "/fleet/dashboard", needs_vehicle: false },
    { key: "vehicles", label: "Liste des véhicules", path: "/fleet/vehicles", needs_vehicle: false },
    { key: "vehicle", label: "Fiche véhicule (tous les véhicules)", path: "/fleet/vehicles/:id", needs_vehicle: true, example: "vehicle" },
    { key: "employee", label: "Fiche employé (tous les employés)", path: "/fleet/employees/:id", needs_vehicle: false, example: "employee" },
    { key: "car-location", label: "Localisation des véhicules", path: "/fleet/car-location", needs_vehicle: false },
    { key: "completeness", label: "Complétude du parc", path: "/fleet/completeness", needs_vehicle: false },
    { key: "employees", label: "Conducteurs", path: "/fleet/employees", needs_vehicle: false },
    { key: "documents", label: "Documents", path: "/fleet/documents", needs_vehicle: false },
    { key: "costs", label: "Coûts", path: "/fleet/costs", needs_vehicle: false },
    { key: "infractions", label: "Infractions", path: "/fleet/infractions", needs_vehicle: false },
  ],
  anchors: [
    ...MENU.map((m) => ({ key: m.key, label: m.label, page_key: null })),
    { key: "sidebar-group.1", label: "Véhicules (groupe)", hint: "Vehicles", page_key: null },
    { key: "sidebar-group.2", label: "Services (groupe)", page_key: null },
    { key: "dashboard.kpis", label: "Indicateurs", page_key: "dashboard" },
    { key: "dashboard.alerts", label: "Bloc Alertes", page_key: "dashboard" },
    { key: "dashboard.date-filter", label: "Filtre de dates", page_key: "dashboard" },
    { key: "vehicles.add-button", label: "Bouton Ajouter un véhicule", page_key: "vehicles" },
    { key: "vehicles.import-button", label: "Bouton Importer", page_key: "vehicles" },
    { key: "vehicles.filters", label: "Filtres", page_key: "vehicles" },
    { key: "vehicles.table", label: "Liste des véhicules", page_key: "vehicles" },
    { key: "vehicle.completeness-card", label: "Carte Complétude", page_key: "vehicle" },
    { key: "vehicle.documents-tab", label: "Onglet Documents", page_key: "vehicle" },
    { key: "vehicle.costs-tab", label: "Onglet Coûts", page_key: "vehicle" },
    { key: "vehicle.edit-button", label: "Bouton Modifier", page_key: "vehicle" },
    { key: "map.zones-button", label: "Bouton Zones", page_key: "car-location" },
    { key: "map.vehicle-list", label: "Liste des véhicules", page_key: "car-location" },
    { key: "map.vehicle-panel", label: "Panneau du véhicule", page_key: "car-location" },
    { key: "map.actions-button", label: "Bouton Actions", page_key: "car-location" },
    { key: "completeness.summary", label: "Résumé", page_key: "completeness" },
    { key: "completeness.filters", label: "Filtres", page_key: "completeness" },
    { key: "completeness.fix-button", label: "Bouton Compléter", page_key: "completeness" },
    { key: "employees.add-button", label: "Bouton Ajouter un conducteur", page_key: "employees" },
    { key: "employees.licence-import", label: "Import des permis", page_key: "employees" },
    { key: "documents.upload-button", label: "Bouton Ajouter un document", page_key: "documents" },
    { key: "costs.import-button", label: "Import des factures", page_key: "costs" },
    { key: "costs.charts", label: "Graphiques", page_key: "costs" },
    { key: "infractions.designate-button", label: "Bouton Désigner", page_key: "infractions" },
  ],
  sidebar_paths: MENU.map((m) => ({ path: m.path, label: m.label, anchor_key: m.key })),
  plans: [
    { value: "free", label: "Gratuit" },
    { value: "essential", label: "Essentiel" },
    { value: "business", label: "Business" },
    { value: "premium", label: "Premium" },
  ],
  capabilities: [
    { value: "telematics", label: "Télématique" },
    { value: "maintenance", label: "Entretien" },
    { value: "reports", label: "Rapports" },
    { value: "fuelcard", label: "Cartes carburant" },
    { value: "infractions", label: "Infractions ANTAI" },
    { value: "aen", label: "Avantage en nature" },
    { value: "ev_energy", label: "Énergie VE" },
    { value: "ai_agents", label: "Donna (IA)" },
  ],
  permissions: [
    { value: "view_vehicles", label: "Voir les véhicules" },
    { value: "manage_vehicles", label: "Gérer les véhicules" },
    { value: "view_map", label: "Voir la carte" },
    { value: "manage_employees", label: "Gérer les conducteurs" },
    { value: "view_costs", label: "Voir les coûts" },
    { value: "manage_documents", label: "Gérer les documents" },
    { value: "manage_infractions", label: "Gérer les infractions" },
  ],
  roles: [
    { value: "owner", label: "Propriétaire du compte" },
    { value: "fleet_manager", label: "Gestionnaire de flotte" },
    { value: "site_manager", label: "Responsable de site" },
    { value: "accountant", label: "Comptable" },
    { value: "driver", label: "Conducteur" },
  ],
  usage_events: [
    { value: "geofence_zone_created", label: "Zone de géorepérage créée" },
    { value: "vehicle_completed", label: "Fiche véhicule complétée" },
    { value: "document_uploaded", label: "Document ajouté" },
    { value: "report_exported", label: "Rapport exporté" },
    { value: "donna_question_asked", label: "Question posée à Donna" },
    { value: "infraction_designated", label: "Infraction désignée" },
    { value: "map_opened", label: "Carte ouverte" },
    { value: "maintenance_planned", label: "Entretien planifié" },
  ],
};

// ── Companies and the fake Fleet population ──────────────────────────────────

const PLAN_CAPABILITIES: Record<string, string[]> = {
  free: [],
  essential: ["maintenance", "reports", "fuelcard"],
  business: ["maintenance", "reports", "fuelcard", "telematics", "infractions", "aen"],
  premium: ["maintenance", "reports", "fuelcard", "telematics", "infractions", "aen", "ev_energy", "ai_agents"],
};

export interface MockCompany {
  id: number;
  name: string;
  plan: string;
  capabilities: string[];
  users: number;
}

export const MOCK_COMPANIES: MockCompany[] = (
  [
    [41, "Dadycar Demo", "premium", 40],
    [12, "Transports Martin", "business", 120],
    [18, "Groupe Lefèvre BTP", "business", 210],
    [23, "Clinique Saint-Roch", "essential", 35],
    [27, "Atlantic Livraisons", "premium", 160],
    [31, "Vertigo Énergie", "premium", 75],
    [35, "Boulangeries Dupain", "free", 18],
    [38, "Sécuri-Pro Services", "business", 95],
    [44, "Agence Horizon Immo", "free", 12],
    [47, "Medi-Sud Ambulances", "essential", 88],
    [52, "Nordis Logistique", "business", 240],
    [55, "Café Lumière", "free", 6],
  ] as const
).map(([id, name, plan, users]) => ({ id, name, plan, capabilities: PLAN_CAPABILITIES[plan], users }));

export interface MockUser {
  id: number;
  company_id: number;
  role: string;
  permissions: string[];
  language: "fr" | "en";
  account_age_days: number;
}

const ROLE_PERMISSIONS: Record<string, string[]> = {
  owner: ["view_vehicles", "manage_vehicles", "view_map", "manage_employees", "view_costs", "manage_documents", "manage_infractions"],
  fleet_manager: ["view_vehicles", "manage_vehicles", "view_map", "manage_employees", "manage_documents", "manage_infractions"],
  site_manager: ["view_vehicles", "view_map", "manage_documents"],
  accountant: ["view_vehicles", "view_costs"],
  driver: ["view_vehicles"],
};

export const MOCK_POPULATION: MockUser[] = (() => {
  const rand = mulberry32(20261016);
  const users: MockUser[] = [];
  let id = 1000;
  for (const company of MOCK_COMPANIES) {
    for (let i = 0; i < company.users; i++) {
      const r = rand();
      const role = i === 0 ? "owner" : r < 0.12 ? "fleet_manager" : r < 0.27 ? "site_manager" : r < 0.35 ? "accountant" : "driver";
      users.push({
        id: id++,
        company_id: company.id,
        role,
        permissions: ROLE_PERMISSIONS[role],
        language: rand() < 0.88 ? "fr" : "en",
        account_age_days: rand() < 0.08 ? Math.floor(rand() * 30) : 30 + Math.floor(rand() * 900),
      });
    }
  }
  return users;
})();

export const MOCK_EXAMPLE_VEHICLES: AnnouncementExampleVehicle[] = [
  ["GC-673-QN", "Peugeot 308 SW"],
  ["FX-218-LM", "Renault Kangoo Van"],
  ["GH-904-TA", "Tesla Model 3"],
  ["FN-552-RC", "Citroën Berlingo"],
  ["GA-117-BZ", "Toyota Yaris Hybrid"],
  ["EZ-730-KD", "Renault Master"],
  ["GD-389-PW", "Volkswagen ID.4"],
  ["FR-461-SE", "Dacia Duster"],
  ["GK-025-VH", "Peugeot e-208"],
  ["FT-886-MJ", "Ford Transit Custom"],
  ["GB-642-NC", "Škoda Octavia Combi"],
  ["GE-271-XU", "Renault Zoe"],
].map(([numberplate, make_model], i) => ({ id: 9001 + i, numberplate, make_model }));

// ── Seed announcements ───────────────────────────────────────────────────────

const step = (id: string, s: Partial<AnnouncementStep> & { title: LocalizedText; body: LocalizedText }): AnnouncementStep => ({
  id,
  subtitle: tx(""),
  icon: null,
  media_url: null,
  media_alt: tx(""),
  anchor_key: null,
  placement: "auto",
  cta_label: tx(""),
  cta_path: null,
  ...s,
});

const MODAL_IMAGE =
  "data:image/svg+xml;utf8," +
  encodeURIComponent(
    `<svg xmlns="http://www.w3.org/2000/svg" width="800" height="450" viewBox="0 0 800 450"><defs><linearGradient id="g" x1="0" x2="1" y1="0" y2="1"><stop offset="0" stop-color="#1d4ed8"/><stop offset="1" stop-color="#7c3aed"/></linearGradient></defs><rect width="800" height="450" fill="url(#g)"/><circle cx="640" cy="110" r="90" fill="#ffffff" opacity="0.12"/><circle cx="160" cy="360" r="140" fill="#ffffff" opacity="0.08"/><text x="60" y="250" font-family="Arial, sans-serif" font-size="64" font-weight="700" fill="#ffffff">Donna</text><text x="60" y="300" font-family="Arial, sans-serif" font-size="26" fill="#dbeafe">Votre assistante de flotte</text></svg>`,
  );

type Seed = Omit<Announcement, "counts" | "updated_at" | "created_at" | "first_published_at"> & {
  created_days_ago: number;
  published_days_ago: number | null;
  /** Days since the current round started (for the growing counts). */
  round_started_days_ago: number | null;
};

const base = {
  body: tx(""),
  badge_text: tx("Nouveau", "New"),
  category: null,
  icon: "Sparkles",
  media_url: null,
  media_alt: tx(""),
  cta_label: tx(""),
  cta_path: null,
  page_key: null,
  target_sidebar_path: null,
  anchor_key: null,
  placement: "auto" as const,
  widget_corner: "bottom_right" as const,
  steps: [] as AnnouncementStep[],
  audience: { ...DEFAULT_AUDIENCE },
  starts_at: null,
  ends_at: null,
  priority: 5,
  rules: { ...DEFAULT_RULES },
  success_event: null,
  reminder: { ...DEFAULT_REMINDER },
  notify: { ...DEFAULT_NOTIFY, message: tx("") },
  round: 1,
};

export function seedAnnouncements(now: number): { seeds: Seed[] } {
  const iso = (days: number) => new Date(now + days * DAY).toISOString();
  const seeds: Seed[] = [
    {
      ...base,
      id: 1,
      key: "completude-du-parc",
      format: "sidebar_spotlight",
      status: "published",
      title: tx("Complétude du parc", "Fleet completeness"),
      body: tx(
        "Voyez d'un coup d'œil les <b>données et documents manquants</b> de vos véhicules, et complétez-les en un clic.",
        "See at a glance the <b>missing data and documents</b> of your vehicles, and complete them in one click.",
      ),
      category: "Documents",
      icon: "ShieldCheck",
      cta_label: tx("Découvrir", "Discover"),
      cta_path: "/fleet/completeness",
      target_sidebar_path: "/fleet/completeness",
      anchor_key: "sidebar.completeness",
      placement: "right",
      audience: { ...DEFAULT_AUDIENCE, permissions: ["view_vehicles"], roles: ["owner", "fleet_manager", "site_manager"] },
      starts_at: iso(-12),
      success_event: "vehicle_completed",
      reminder: { enabled: true, after_days: 7, format: "banner", max_reminders: 2 },
      created_by: "Mhamed B.",
      created_days_ago: 15,
      published_days_ago: 12,
      round_started_days_ago: 12,
    },
    {
      ...base,
      id: 2,
      key: "carte-temps-reel",
      format: "badge",
      status: "published",
      title: tx("Nouvelle carte en temps réel", "New live map"),
      badge_text: tx("Nouveau", "New"),
      category: "Télématique",
      icon: "Map",
      anchor_key: "sidebar.car-location",
      target_sidebar_path: "/fleet/car-location",
      audience: { ...DEFAULT_AUDIENCE, capabilities_required: ["telematics"], permissions: ["view_map"] },
      starts_at: iso(-20),
      ends_at: iso(25),
      rules: { ...DEFAULT_RULES, hide_after_page_visit: true },
      success_event: "map_opened",
      created_by: "Sarah K.",
      created_days_ago: 22,
      published_days_ago: 20,
      round_started_days_ago: 20,
    },
    {
      ...base,
      id: 3,
      key: "maintenance-planifiee",
      format: "banner",
      status: "published",
      title: tx("Maintenance planifiée dimanche", "Planned maintenance on Sunday"),
      body: tx(
        "Fleet sera indisponible <b>dimanche de 6 h à 8 h</b> pour une mise à jour.",
        "Fleet will be unavailable <b>on Sunday from 6 to 8 am</b> for an update.",
      ),
      icon: "Wrench",
      badge_text: tx("Info", "Info"),
      audience: { ...DEFAULT_AUDIENCE, everyone_confirmed: true },
      starts_at: iso(3),
      ends_at: iso(6),
      priority: 8,
      rules: { ...DEFAULT_RULES, max_impressions: 5 },
      created_by: "Mhamed B.",
      created_days_ago: 2,
      published_days_ago: 1,
      round_started_days_ago: null,
    },
    {
      ...base,
      id: 4,
      key: "lancement-donna",
      format: "modal",
      status: "published",
      title: tx("Donna, votre assistante de flotte", "Donna, your fleet assistant"),
      body: tx(
        "Posez vos questions en français : <i>« Quels véhicules ont leur contrôle technique ce mois-ci ? »</i>. Donna répond avec vos données.",
        "Ask your questions in plain words: <i>\"Which vehicles have their inspection this month?\"</i>. Donna answers with your data.",
      ),
      badge_text: tx("Nouveau", "New"),
      category: "IA",
      icon: "Bot",
      media_url: MODAL_IMAGE,
      media_alt: tx("Illustration : l'assistante Donna", "Illustration: the Donna assistant"),
      cta_label: tx("Essayer Donna", "Try Donna"),
      cta_path: "/fleet/donna",
      audience: { ...DEFAULT_AUDIENCE, plans: ["premium"], roles: ["owner", "fleet_manager"] },
      starts_at: iso(-6),
      ends_at: iso(24),
      priority: 9,
      success_event: "donna_question_asked",
      reminder: { enabled: true, after_days: 5, format: "badge", max_reminders: 1 },
      notify: { enabled: true, channels: ["in_app", "email"], message: tx("Découvrez Donna, votre assistante de flotte.", "Meet Donna, your fleet assistant.") },
      created_by: "Mhamed B.",
      created_days_ago: 9,
      published_days_ago: 6,
      round_started_days_ago: 6,
    },
    {
      ...base,
      id: 5,
      key: "decouvrir-fiche-vehicule",
      format: "page_widget",
      status: "published",
      title: tx("Découvrir la fiche véhicule", "Discover the vehicle sheet"),
      icon: "Car",
      page_key: "vehicle",
      widget_corner: "bottom_right",
      steps: [
        step("s5-1", {
          title: tx("Tout votre véhicule au même endroit", "Your whole vehicle in one place"),
          body: tx("Identité, contrats, documents et coûts : la fiche rassemble tout.", "Identity, contracts, documents and costs: the sheet gathers everything."),
          icon: "Car",
        }),
        step("s5-2", {
          title: tx("Ce qu'il manque", "What's missing"),
          body: tx("La carte <b>Complétude</b> liste les informations à compléter.", "The <b>Completeness</b> card lists the information to complete."),
          anchor_key: "vehicle.completeness-card",
          placement: "left",
          icon: "ShieldCheck",
        }),
        step("s5-3", {
          title: tx("Vos documents", "Your documents"),
          body: tx("Ajoutez carte grise, assurance et contrats dans l'onglet Documents.", "Add registration, insurance and contracts in the Documents tab."),
          anchor_key: "vehicle.documents-tab",
          placement: "bottom",
          icon: "FileText",
          cta_label: tx("Ajouter un document", "Add a document"),
          cta_path: "/fleet/documents",
        }),
      ],
      audience: { ...DEFAULT_AUDIENCE, permissions: ["manage_vehicles"] },
      starts_at: iso(-30),
      success_event: "document_uploaded",
      created_by: "Sarah K.",
      created_days_ago: 33,
      published_days_ago: 30,
      round_started_days_ago: 9,
      round: 2,
    },
    {
      ...base,
      id: 6,
      key: "zones-de-georeperage",
      format: "tour",
      status: "draft",
      title: tx("Zones de géorepérage", "Geofencing zones"),
      category: "Télématique",
      icon: "MapPin",
      page_key: "car-location",
      steps: [
        step("s6-1", {
          title: tx("Vos zones sur la carte", "Your zones on the map"),
          body: tx("Affichez vos zones de géorepérage sur la carte.", "Show your geofencing zones on the map."),
          anchor_key: "map.zones-button",
          placement: "bottom",
          icon: "MapPin",
        }),
      ],
      audience: { ...DEFAULT_AUDIENCE, capabilities_required: ["telematics"], permissions: ["view_map"] },
      success_event: "geofence_zone_created",
      created_by: "Mhamed B.",
      created_days_ago: 1,
      published_days_ago: null,
      round_started_days_ago: null,
      round: 0,
    },
    {
      ...base,
      id: 7,
      key: "nouveau-tableau-de-bord",
      format: "banner",
      status: "published",
      title: tx("Nouveau tableau de bord", "New dashboard"),
      body: tx("Votre tableau de bord a fait peau neuve : <b>plus clair, plus rapide</b>.", "Your dashboard got a makeover: <b>clearer, faster</b>."),
      icon: "BarChart3",
      page_key: "dashboard",
      cta_label: tx("Voir les nouveautés", "See what's new"),
      cta_path: "/fleet/dashboard",
      audience: { ...DEFAULT_AUDIENCE, everyone_confirmed: true },
      starts_at: iso(-45),
      ends_at: iso(-15),
      success_event: "report_exported",
      created_by: "Sarah K.",
      created_days_ago: 50,
      published_days_ago: 45,
      round_started_days_ago: 45,
    },
    {
      ...base,
      id: 8,
      key: "ancienne-offre-essentiel",
      format: "modal",
      status: "archived",
      title: tx("L'offre Essentiel évolue", "The Essential plan evolves"),
      body: tx("L'offre Essentiel inclut désormais les <b>rapports</b> et les <b>cartes carburant</b>.", "The Essential plan now includes <b>reports</b> and <b>fuel cards</b>."),
      icon: "Gift",
      cta_label: tx("Voir les offres", "See the plans"),
      cta_path: "/fleet/settings/plans",
      audience: { ...DEFAULT_AUDIENCE, plans: ["essential"], capabilities_missing: ["telematics"] },
      starts_at: iso(-120),
      ends_at: iso(-60),
      success_event: "report_exported",
      created_by: "Mhamed B.",
      created_days_ago: 125,
      published_days_ago: 120,
      round_started_days_ago: 120,
    },
  ];
  return { seeds };
}

export function seedHistory(seeds: Seed[], now: number): Record<number, AnnouncementHistoryEntry[]> {
  const iso = (days: number) => new Date(now - days * DAY).toISOString();
  let id = 1;
  const out: Record<number, AnnouncementHistoryEntry[]> = {};
  for (const s of seeds) {
    const entries: AnnouncementHistoryEntry[] = [{ id: id++, action: "created", by: s.created_by, at: iso(s.created_days_ago), detail: null }];
    if (s.published_days_ago !== null) {
      entries.push({ id: id++, action: "updated", by: s.created_by, at: iso(s.published_days_ago + 0.5), detail: "Texte, Audience" });
      entries.push({ id: id++, action: "published", by: "Mhamed B.", at: iso(s.published_days_ago), detail: null });
    }
    if (s.round > 1 && s.round_started_days_ago !== null) {
      entries.push({ id: id++, action: "reset", by: "Sarah K.", at: iso(s.round_started_days_ago), detail: "Nouvelle version de la fiche véhicule" });
    }
    if (s.status === "archived") entries.push({ id: id++, action: "archived", by: "Mhamed B.", at: iso(55), detail: null });
    out[s.id] = entries.reverse();
  }
  return out;
}

export type { Seed };
