/* global React, seedRng, FOST_CATALOG, DOSSIERS, CLIENTS, CITIES */
// Visite Technique — data fixtures (schema aligned with backend)

// Equipment taxonomy (from DetectedEquipment.category comment)
const VT_CATEGORIES = {
  pac_air_air:    { label: 'PAC air/air',        icon: 'pac', tone: 'signal' },
  pac_air_eau:    { label: 'PAC air/eau',        icon: 'pac', tone: 'signal' },
  panneau_pv:     { label: 'Panneau PV',         icon: 'pv',  tone: 'amber'  },
  chaudiere:      { label: 'Chaudière',          icon: 'flame', tone: 'rouge' },
  groupe_froid:   { label: 'Groupe froid',       icon: 'cold', tone: 'plasma' },
  clim:           { label: 'Climatisation',      icon: 'wind', tone: 'plasma' },
  ballon_thermo:  { label: 'Ballon thermo.',     icon: 'tank', tone: 'signal' },
  cta:            { label: 'CTA',                icon: 'vent', tone: 'neutral' },
  onduleur:       { label: 'Onduleur',           icon: 'bolt', tone: 'copper' },
  compteur:       { label: 'Compteur',           icon: 'meter', tone: 'neutral' },
  enveloppe:      { label: 'Enveloppe bât.',     icon: 'wall', tone: 'neutral' },
};

const VT_TECHS = [
  { email: 'k.demian@audits-energies.fr',  name: 'Kevin Démian',   init: 'KD', truck: 'VK-312' },
  { email: 't.aubert@audits-energies.fr',  name: 'Thomas Aubert',  init: 'TA', truck: 'VK-118' },
  { email: 'j.noguera@audits-energies.fr', name: 'Julie Noguera',  init: 'JN', truck: 'VK-204' },
  { email: 'm.ferrand@audits-energies.fr', name: 'Mélissa Ferrand',init: 'MF', truck: 'VK-077' },
];

// Generate a rich set of visites
function generateVT() {
  const rng = seedRng('vt-v1');
  const STATUSES = ['completed', 'completed', 'completed', 'processing', 'recording', 'draft', 'completed'];
  const TYPES = ['video', 'video', 'video', 'audio', 'mixed'];
  const out = [];
  const n = 24;
  for (let i = 1; i <= n; i++) {
    const tech = VT_TECHS[Math.floor(rng() * VT_TECHS.length)];
    const city = CITIES[Math.floor(rng() * CITIES.length)];
    const client = CLIENTS[Math.floor(rng() * CLIENTS.length)];
    const dossier = DOSSIERS[Math.floor(rng() * DOSSIERS.length)];
    const status = STATUSES[Math.floor(rng() * STATUSES.length)];
    const type = TYPES[Math.floor(rng() * TYPES.length)];
    const duration = 180 + Math.floor(rng() * 2400); // 3–45 min
    const equipCount = 1 + Math.floor(rng() * 6);
    const photoCount = 4 + Math.floor(rng() * 18);
    const frameCount = 40 + Math.floor(rng() * 240);
    const daysAgo = Math.floor(rng() * 28);
    const startedAt = new Date(Date.now() - daysAgo * 86400000 - Math.floor(rng() * 8 * 3600000));
    const completedAt = status === 'completed' ? new Date(startedAt.getTime() + duration * 1000 + 120 * 1000) : null;
    const hasSatellite = rng() > 0.35;
    const roofArea = hasSatellite ? 40 + Math.floor(rng() * 260) : null;
    const pvPotential = hasSatellite ? Math.round(roofArea * 0.18 * 1100) : null;
    const cumacReco = Math.round(dossier.cumac * (0.4 + rng() * 0.8));
    out.push({
      ref: `VT-2026-${String(i).padStart(3, '0')}`,
      dossierRef: dossier.ref,
      dossierFost: dossier.fost,
      client: client.name,
      org: client.org,
      clientAddress: `${Math.floor(1 + rng() * 180)} ${['rue', 'avenue', 'boulevard', 'chemin'][Math.floor(rng() * 4)]} ${['des Lilas', 'du Général', 'Victor Hugo', 'de la République', 'des Platanes', 'du Port', 'de la Gare'][Math.floor(rng() * 7)]}, ${city.name}`,
      city: city.name,
      zone: city.zone,
      lat: city.lat + (rng() - 0.5) * 0.1,
      lon: city.lng + (rng() - 0.5) * 0.1,
      status,
      type,
      technicianName: tech.name,
      technicianEmail: tech.email,
      technicianInit: tech.init,
      truck: tech.truck,
      startedAt: startedAt.toISOString(),
      completedAt: completedAt ? completedAt.toISOString() : null,
      durationSeconds: duration,
      mediaCount: { video: type !== 'audio' ? 1 : 0, audio: 1, photo: photoCount, frame: frameCount },
      equipmentsDetected: equipCount,
      ocrResults: Math.floor(equipCount * (0.5 + rng() * 0.9)),
      satellite: hasSatellite ? { roofArea, pvPotential, orientation: ['S', 'SE', 'SO', 'E', 'O'][Math.floor(rng() * 5)], tilt: 15 + Math.floor(rng() * 25) } : null,
      cumacReco,
      reportGenerated: status === 'completed' && rng() > 0.3,
      crmSynced: status === 'completed' && rng() > 0.4,
      aiConfidence: 0.5 + rng() * 0.49,
      network: ['4G', '5G', '4G', 'WiFi', '3G'][Math.floor(rng() * 5)],
      battery: 30 + Math.floor(rng() * 70),
    });
  }
  return out.sort((a, b) => new Date(b.startedAt) - new Date(a.startedAt));
}

const VISITES = generateVT();

// The HERO visite — a fully detailed one we'll reference everywhere
const VT_HERO_REF = 'VT-2026-007';

// Detailed detected equipments for the hero visite
const VT_HERO_EQUIPMENTS = [
  {
    id: 'eq-1',
    source: 'vision',
    confidence: 0.94,
    category: 'pac_air_eau',
    brand: 'Daikin',
    model: 'EBLQ011CAW1',
    serialNumber: 'DK-2021-8837491',
    power_kw: 11,
    refrigerant: 'R-32',
    yearEstimated: 2021,
    energyClass: 'A++',
    rawOcrText: 'DAIKIN ALTHERMA 3\nEBLQ011CAW1\nS/N: DK-2021-8837491\nR32 / 1,4kg\nP nominale: 11 kW\n2021/08',
    frameTimestamp: 47.2,
    boundingBox: { x: 0.24, y: 0.31, w: 0.38, h: 0.24 },
    validated: true,
    validatedBy: 'K. Démian',
    fostCodesSuggested: [
      { code: 'BAR-TH-171', label: 'PAC air/eau', kwhCumac: 86400 },
      { code: 'BAR-TH-159', label: 'Régulateur thermique', kwhCumac: 12800 },
    ],
    thumb: { h: 145 }, // hue for placeholder
  },
  {
    id: 'eq-2',
    source: 'vision',
    confidence: 0.88,
    category: 'ballon_thermo',
    brand: 'Atlantic',
    model: 'Odyssée 270L',
    serialNumber: 'AT-19-K-2274',
    power_kw: 2.5,
    yearEstimated: 2019,
    energyClass: 'A+',
    rawOcrText: 'ATLANTIC\nODYSSEE 270\nC.E.T. split\nCOP 3,4\nS/N: AT-19-K-2274\n270 L',
    frameTimestamp: 112.8,
    boundingBox: { x: 0.18, y: 0.22, w: 0.45, h: 0.58 },
    validated: true,
    validatedBy: 'K. Démian',
    fostCodesSuggested: [
      { code: 'BAR-TH-148', label: 'Chauffe-eau thermodynamique', kwhCumac: 18600 },
    ],
    thumb: { h: 210 },
  },
  {
    id: 'eq-3',
    source: 'ocr',
    confidence: 0.71,
    category: 'compteur',
    brand: 'Enedis',
    model: 'Linky G3',
    rawOcrText: 'LINKY\nN° 0612 487 330 001\nEnedis\nIP2 X B\nIK04',
    frameTimestamp: 148.5,
    validated: true,
    validatedBy: 'K. Démian',
    fostCodesSuggested: [],
    thumb: { h: 55 },
  },
  {
    id: 'eq-4',
    source: 'audio_nlp',
    confidence: 0.62,
    category: 'chaudiere',
    brand: 'Frisquet',
    model: 'Hydroconfort (à remplacer)',
    yearEstimated: 2008,
    rawOcrText: null,
    frameTimestamp: 201.3,
    validated: false,
    fostCodesSuggested: [
      { code: 'BAR-TH-104', label: 'PAC air/eau remplacement chaudière', kwhCumac: 98000 },
    ],
    thumb: { h: 10 },
    notes: 'Mentionnée par le propriétaire. À confirmer visuellement — fiche FOST BAR-TH-104 éligible.',
  },
  {
    id: 'eq-5',
    source: 'vision',
    confidence: 0.52,
    category: 'panneau_pv',
    brand: 'inconnu',
    model: 'non plaqué',
    yearEstimated: null,
    frameTimestamp: 288.1,
    validated: false,
    fostCodesSuggested: [],
    thumb: { h: 38 },
    notes: 'Toiture vue en survol drone — à croiser avec module satellite.',
  },
];

// Audio transcript segments (with speakers + entities)
const VT_HERO_TRANSCRIPT = {
  language: 'fr',
  speakers: [
    { id: 'S1', label: 'K. Démian',       role: 'tech' },
    { id: 'S2', label: 'M. Bourdillon',   role: 'client' },
  ],
  segments: [
    { start: 2.1,   end: 8.4,   speaker: 'S1', text: 'Bonjour Monsieur Bourdillon, je suis Kevin Démian du bureau d\'études Audits-Énergies. On est là pour la visite technique de votre maison.', entities: [] },
    { start: 9.2,   end: 14.8,  speaker: 'S2', text: 'Ah oui très bien, entrez. Vous voulez qu\'on commence par la chaudière ?', entities: [{ type: 'equipment', value: 'chaudière', confidence: 0.94 }] },
    { start: 15.1,  end: 22.6,  speaker: 'S1', text: 'On va faire un tour complet. D\'abord le tableau, ensuite la PAC si vous en avez une, puis la toiture. C\'est une maison de quelle année ?', entities: [{ type: 'equipment', value: 'PAC', confidence: 0.88 }] },
    { start: 23.1,  end: 28.9,  speaker: 'S2', text: '1978, on l\'a rénovée en 2003 mais la chaudière Frisquet date de 2008 et elle commence à fatiguer.', entities: [
      { type: 'date', value: '1978', confidence: 0.99 },
      { type: 'date', value: '2003', confidence: 0.99 },
      { type: 'date', value: '2008', confidence: 0.99 },
      { type: 'equipment', value: 'chaudière Frisquet', confidence: 0.96 },
      { type: 'problem', value: 'fatigue', confidence: 0.78 },
    ]},
    { start: 45.8,  end: 52.3,  speaker: 'S1', text: 'OK là on est devant la PAC Daikin Altherma, 11 kW d\'après la plaque, installée en 2021. Elle est sous garantie jusqu\'en 2026.', entities: [
      { type: 'equipment', value: 'PAC Daikin Altherma', confidence: 0.99 },
      { type: 'spec', value: '11 kW', confidence: 0.99 },
      { type: 'date', value: '2021', confidence: 0.99 },
    ]},
    { start: 98.4,  end: 108.1, speaker: 'S2', text: 'Pour le budget on peut aller jusqu\'à 18 000 euros si on change la chaudière. Ma femme voudrait bien mettre du solaire aussi.', entities: [
      { type: 'budget', value: '18 000 €', confidence: 0.99 },
      { type: 'equipment', value: 'solaire', confidence: 0.82 },
    ]},
    { start: 110.5, end: 118.7, speaker: 'S1', text: 'Bon à savoir. Je note. Le ballon thermodynamique Atlantic est récent, 2019, on le garde. Passons à la toiture.', entities: [
      { type: 'equipment', value: 'ballon thermodynamique Atlantic', confidence: 0.98 },
      { type: 'date', value: '2019', confidence: 0.99 },
      { type: 'action', value: 'garder', confidence: 0.85 },
    ]},
    { start: 180.2, end: 192.6, speaker: 'S1', text: 'Toiture exposée plein sud, pente 30 degrés à peu près, environ 85 mètres carrés utilisables. Pas d\'ombre portée. Parfait pour du photovoltaïque.', entities: [
      { type: 'spec', value: 'plein sud', confidence: 0.95 },
      { type: 'spec', value: '30°', confidence: 0.92 },
      { type: 'spec', value: '85 m²', confidence: 0.94 },
      { type: 'equipment', value: 'photovoltaïque', confidence: 0.96 },
    ]},
    { start: 240.3, end: 252.8, speaker: 'S2', text: 'Vous pensez que c\'est jouable avec les aides ? On avait vu que Ma Prime Rénov\' c\'était plus ce que c\'était.', entities: [
      { type: 'subvention', value: 'MaPrimeRénov\'', confidence: 0.99 },
    ]},
    { start: 253.9, end: 271.4, speaker: 'S1', text: 'Avec les CEE bonifiés coup de pouce chauffage, vous avez environ 5 200 euros rien que sur la PAC en remplacement, plus MaPrimeRénov\' et l\'éco-PTZ. Je vous chiffre tout ça au bureau.', entities: [
      { type: 'subvention', value: 'CEE coup de pouce', confidence: 0.97 },
      { type: 'budget', value: '5 200 €', confidence: 0.98 },
      { type: 'subvention', value: 'éco-PTZ', confidence: 0.96 },
      { type: 'action', value: 'chiffrage', confidence: 0.88 },
    ]},
  ],
  sentiment: { overall: 'positive', score: 0.62 },
};

// Hero visite metadata (fully-specified)
const VT_HERO = {
  ref: 'VT-2026-007',
  dossierRef: 'DOS-2026-024',
  client: 'M. Bourdillon',
  clientAddress: '14 rue des Platanes, Nantes',
  city: 'Nantes',
  zone: 'H2a',
  lat: 47.2182,
  lon: -1.5523,
  status: 'completed',
  type: 'mixed',
  technicianName: 'Kevin Démian',
  technicianEmail: 'k.demian@audits-energies.fr',
  technicianInit: 'KD',
  truck: 'VK-312',
  startedAt: new Date(Date.now() - 2 * 86400000 - 3 * 3600000).toISOString(),
  completedAt: new Date(Date.now() - 2 * 86400000 - 2.3 * 3600000).toISOString(),
  durationSeconds: 42 * 60 + 18,
  network: '4G',
  battery: 68,
  consentRecorded: true,
  consentTimestamp: new Date(Date.now() - 2 * 86400000 - 3.05 * 3600000).toISOString(),
  satellite: {
    roofArea: 112,
    usableArea: 85,
    orientation: 'S',
    tilt: 30,
    pvPotentialKwh: 14800,
    pvgisSource: 'PVGIS-SARAH2 · 2005–2020',
    shadowFactor: 0.04,
  },
  calpinage: {
    panels: 16,
    panelModel: 'Trina Vertex S 405W',
    panelW: 405,
    rows: 2,
    cols: 8,
    totalKwc: 6.48,
    estimatedProduction: 7320,
    selfConsumption: 0.62,
    injectionSurplus: true,
  },
  recommendations: [
    { fostCode: 'BAR-TH-104', label: 'Remplacement chaudière par PAC air/eau', kwhCumac: 98000, priority: 1, confidence: 0.94 },
    { fostCode: 'BAR-TH-137', label: 'Installation photovoltaïque 6,48 kWc', kwhCumac: 62400, priority: 2, confidence: 0.89 },
    { fostCode: 'BAR-EN-101', label: 'Isolation combles aménagés', kwhCumac: 21700, priority: 3, confidence: 0.71 },
  ],
  aiSummary: "Maison T5 de 148 m² à Nantes (zone H2a), occupée par M. Bourdillon et son épouse. PAC air/eau Daikin Altherma 11 kW installée en 2021 fonctionnelle, ballon thermodynamique Atlantic de 2019 à conserver. La chaudière Frisquet de 2008 est en fin de vie — remplacement par PAC éligible au coup de pouce chauffage (BAR-TH-104, ~98 000 kWh cumac). Toiture plein sud, 30° de pente, 85 m² utilisables sans ombrage : potentiel 6,48 kWc (16 panneaux 405 W) avec ~62 % d'autoconsommation estimée. Budget évoqué par le client : 18 000 €. Ouverture forte sur le solaire. Dossier à privilégier.",
  speakerMoment: { start: 98.4, end: 108.1 }, // key moment (budget)
};

Object.assign(window, {
  VT_CATEGORIES, VT_TECHS, VISITES, VT_HERO_REF, VT_HERO, VT_HERO_EQUIPMENTS, VT_HERO_TRANSCRIPT,
});
