/* MIRAI — Rastreo IA · datos mock + servicio
 *
 * Aislado a propósito (MVP, sin scraping ni APIs reales). Cuando exista backend,
 * reemplazar `searchProperties(criteria)` por un fetch que devuelva la misma forma.
 *
 * Tipos (JSDoc):
 * @typedef {Object} RastreoCriteria
 * @property {string} cliente
 * @property {string} operacion
 * @property {string} tipo
 * @property {string} presupuesto
 * @property {string[]} zonas
 * @property {string} dormitorios
 * @property {string} ambientes
 * @property {string} superficie
 * @property {string[]} caracteristicas
 * @property {string} observaciones
 *
 * @typedef {Object} RastreoProperty
 * @property {string} id
 * @property {string} portal      // key de RASTREO_SOURCES
 * @property {string} title
 * @property {string} location
 * @property {string} price
 * @property {number} amb
 * @property {number} dorm
 * @property {number} sup
 * @property {number} match       // % de coincidencia
 * @property {boolean} verified
 * @property {string} image
 *
 * @typedef {Object} RastreoResult
 * @property {RastreoProperty[]} properties
 * @property {{ total:number, verified:number, label:string }} summary
 */

// ---- Opciones de los selects / chips ----
const RASTREO_OPERACIONES = ["Comprar", "Alquilar", "Alquiler temporario"];
const RASTREO_TIPOS = ["Departamento", "Casa", "PH", "Local comercial", "Oficina", "Terreno"];
const RASTREO_PRESUPUESTOS = [
  "USD 100.000 - USD 150.000",
  "USD 150.000 - USD 190.000",
  "USD 190.000 - USD 240.000",
  "USD 240.000 - USD 300.000",
  "USD 300.000 o más",
];
const RASTREO_DORMITORIOS = ["1 dormitorio", "2 dormitorios", "3 dormitorios", "4+ dormitorios"];
const RASTREO_AMBIENTES = ["1 ambiente", "2 ambientes", "3 ambientes", "4 ambientes", "5+ ambientes"];
const RASTREO_ZONAS = ["Palermo", "Belgrano", "Núñez", "Recoleta", "Caballito", "Colegiales", "Villa Urquiza", "Saavedra", "Puerto Madero", "Villa Crespo"];
const RASTREO_CARACTERISTICAS = ["Muy luminoso", "Estilo moderno", "Balcón", "Cocina integrada", "Cochera", "Pileta", "Amenities", "A estrenar", "Apto profesional", "Pet friendly"];

// ---- Portales a rastrear ----
const RASTREO_SOURCES = [
  { key: "meli", label: "Mercado Libre", short: "ML", color: "#FFE600", ink: "#2D3277" },
  { key: "zonaprop", label: "ZonaProp", short: "Z", color: "#FF5722", ink: "#fff" },
  { key: "argenprop", label: "Argenprop", short: "A", color: "#00B7A9", ink: "#fff" },
  { key: "tokko", label: "Tokko Broker", short: "T", color: "#111111", ink: "#fff" },
];
const RASTREO_SOURCE_MAP = RASTREO_SOURCES.reduce((m, s) => { m[s.key] = s; return m; }, {});

// ---- Pasos del asistente (Emma) ----
const RASTREO_EMMA_STEPS = [
  "Buscar coincidencias en los portales seleccionados",
  "Comparar características y estilo visual",
  "Validar disponibilidad y precio actualizado",
  "Preparar un informe con links directos",
];

// ---- Criterio inicial (precargado, igual a la referencia) ----
const RASTREO_DEFAULT_CRITERIA = {
  cliente: "María Fernanda R.",
  operacion: "Comprar",
  tipo: "Departamento",
  presupuesto: "USD 190.000 - USD 240.000",
  zonas: ["Palermo", "Belgrano", "Núñez"],
  dormitorios: "2 dormitorios",
  ambientes: "3 ambientes",
  superficie: "70 m²",
  caracteristicas: ["Muy luminoso", "Estilo moderno", "Balcón", "Cocina integrada", "Cochera"],
  observaciones:
    "Busca un departamento moderno, bien iluminado, con buena distribución de ambientes. Preferentemente con balcón y cocina integrada. Prioriza luz natural y espacios amplios.",
};

// Imágenes de referencia precargadas (mock).
const rtImg = (id) => `https://images.unsplash.com/${id}?auto=format&fit=crop&w=640&q=70`;
const RASTREO_REF_IMAGES = [
  { id: "r1", src: rtImg("photo-1502672260266-1c1ef2d93688") },
  { id: "r2", src: rtImg("photo-1493809842364-78817add7ffb") },
  { id: "r3", src: rtImg("photo-1522708323590-d24dbb6b0267") },
];

// ---- Propiedades mock (resultado del rastreo) ----
const RASTREO_PROPERTIES = [
  { id: "p1", portal: "zonaprop", title: "Departamento 3 ambientes con balcón aterrazado", location: "Palermo, CABA", price: "USD 219.000", amb: 3, dorm: 2, sup: 72, match: 96, verified: true, image: rtImg("photo-1502672260266-1c1ef2d93688") },
  { id: "p2", portal: "meli", title: "Depto. moderno y luminoso en excelente ubicación", location: "Belgrano, CABA", price: "USD 205.000", amb: 3, dorm: 2, sup: 73, match: 97, verified: true, image: rtImg("photo-1493809842364-78817add7ffb") },
  { id: "p3", portal: "argenprop", title: "3 ambientes a estrenar con amenities", location: "Núñez, CABA", price: "USD 237.000", amb: 3, dorm: 2, sup: 68, match: 86, verified: true, image: rtImg("photo-1484154218962-a197022b5858") },
  { id: "p4", portal: "zonaprop", title: "Luminoso 3 amb. con cochera y baulera", location: "Palermo, CABA", price: "USD 228.000", amb: 3, dorm: 2, sup: 75, match: 92, verified: true, image: rtImg("photo-1560448204-e02f11c3d0e2") },
  { id: "p5", portal: "tokko", title: "Depto. premium con balcón y parrilla propia", location: "Belgrano, CABA", price: "USD 240.000", amb: 3, dorm: 2, sup: 78, match: 90, verified: true, image: rtImg("photo-1505691938895-1758d7feb511") },
  { id: "p6", portal: "meli", title: "Moderno 3 ambientes con vista al parque", location: "Núñez, CABA", price: "USD 212.000", amb: 3, dorm: 2, sup: 70, match: 88, verified: false, image: rtImg("photo-1522708323590-d24dbb6b0267") },
];

/**
 * Servicio mock de rastreo. Hoy ignora `criteria` y devuelve resultados simulados
 * tras un breve delay; mantené esta firma para enchufar el backend real luego.
 * @param {RastreoCriteria} criteria
 * @returns {Promise<RastreoResult>}
 */
function searchProperties(criteria) {
  return new Promise((resolve) => {
    setTimeout(() => {
      const properties = RASTREO_PROPERTIES;
      const verified = properties.filter((p) => p.verified).length;
      resolve({
        properties,
        summary: {
          total: 12,
          verified: verified,
          label: `Rastreo completado · 12 coincidencias · ${verified} verificadas`,
        },
      });
    }, 1600);
  });
}

Object.assign(window, {
  RASTREO_OPERACIONES, RASTREO_TIPOS, RASTREO_PRESUPUESTOS, RASTREO_DORMITORIOS, RASTREO_AMBIENTES,
  RASTREO_ZONAS, RASTREO_CARACTERISTICAS, RASTREO_SOURCES, RASTREO_SOURCE_MAP, RASTREO_EMMA_STEPS,
  RASTREO_DEFAULT_CRITERIA, RASTREO_REF_IMAGES, RASTREO_PROPERTIES, searchProperties,
});
