/* Modelo de datos del establecimiento — Argentina (Pampa / Córdoba demo). */
const FARM = {
  name: "Estancia El Quebracho",
  location: "Río Segundo, Córdoba, Argentina",
  coords: "31.42°S, 63.24°O",
  season: "2025/26 · Campaña gruesa + fina",
  totalArea: 1160,
  cultivated: 925,
  fieldsCount: 8,
  avgNDVI: 0.61,
  predictedYield: 2840, // toneladas equivalentes (mix)
  yieldConfidence: 88,
  waterUsedPct: 58,
  alerts: 3,
};

// 8 lotes — entidades principales. Estado: healthy | watch | stress
const FIELDS = [
  { id: "F-01", name: "Lote Norte",   crop: "Soja",    area: 320, ndvi: 0.72, moisture: 62, yieldPred: 3.8,  unit: "t/ha", status: "healthy", change: +5, zone: "Norte" },
  { id: "F-02", name: "Lote Sur",     crop: "Maíz",    area: 280, ndvi: 0.61, moisture: 48, yieldPred: 9.4,  unit: "t/ha", status: "watch",   change: -2, zone: "Sur" },
  { id: "F-03", name: "Potrero Oeste",crop: "Trigo",   area: 125, ndvi: 0.58, moisture: 41, yieldPred: 4.1,  unit: "t/ha", status: "watch",   change: -1, zone: "Oeste" },
  { id: "F-04", name: "Lote Este",    crop: "Soja",    area: 95,  ndvi: 0.45, moisture: 33, yieldPred: 2.6,  unit: "t/ha", status: "stress",  change: -8, zone: "Este" },
  { id: "F-05", name: "Campo Central",crop: "Maíz",    area: 210, ndvi: 0.68, moisture: 55, yieldPred: 10.2, unit: "t/ha", status: "healthy", change: +3, zone: "Centro" },
  { id: "F-06", name: "Bajo del Tala",crop: "Girasol", area: 78,  ndvi: 0.64, moisture: 50, yieldPred: 2.4,  unit: "t/ha", status: "healthy", change: +2, zone: "Sur" },
  { id: "F-07", name: "Media Loma",   crop: "Sorgo",   area: 110, ndvi: 0.38, moisture: 29, yieldPred: 4.0,  unit: "t/ha", status: "stress",  change: -11, zone: "Oeste" },
  { id: "F-08", name: "Pastura Alta", crop: "Alfalfa", area: 88,  ndvi: 0.74, moisture: 64, yieldPred: 9.0,  unit: "t/ha", status: "healthy", change: +4, zone: "Norte" },
];

const STATUS = {
  healthy: { label: "Saludable", color: "#4f8a2f", bg: "rgba(123,180,60,0.16)" },
  watch:   { label: "Vigilar",   color: "#b58a16", bg: "rgba(214,170,40,0.18)" },
  stress:  { label: "Estrés",    color: "#c0492f", bg: "rgba(200,90,60,0.16)" },
};

// Clima 7 días (demo Córdoba)
const WEATHER = [
  { day: "Lun", t: 24, lo: 11, cond: "sun",   rain: 5,  wind: 14, et: 4.2 },
  { day: "Mar", t: 26, lo: 12, cond: "sun",   rain: 0,  wind: 12, et: 4.6 },
  { day: "Mié", t: 23, lo: 13, cond: "cloud", rain: 25, wind: 18, et: 3.4 },
  { day: "Jue", t: 19, lo: 10, cond: "rain",  rain: 70, wind: 22, et: 2.1 },
  { day: "Vie", t: 18, lo: 9,  cond: "cloud", rain: 20, wind: 16, et: 2.8 },
  { day: "Sáb", t: 22, lo: 10, cond: "sun",   rain: 8,  wind: 11, et: 4.0 },
  { day: "Dom", t: 25, lo: 12, cond: "sun",   rain: 0,  wind: 10, et: 4.5 },
];

// Vigilancia de plagas y enfermedades (Argentina)
const PESTS = [
  { name: "Roya asiática",        type: "Enfermedad", field: "Lote Este",     crop: "Soja",    risk: 78, level: "high",   trend: "up",   action: "Monitorear y fungicida si umbral" },
  { name: "Isoca medidora",       type: "Plaga",      field: "Lote Norte",    crop: "Soja",    risk: 62, level: "medium", trend: "up",   action: "Muestreo de larvas / umbral" },
  { name: "Chinche de los cuernos", type: "Plaga",    field: "Lote Norte",    crop: "Soja",    risk: 55, level: "medium", trend: "flat", action: "Revisar en R3–R5" },
  { name: "Cogollero",            type: "Plaga",      field: "Lote Sur",      crop: "Maíz",    risk: 48, level: "medium", trend: "down", action: "Trampas + refugio Bt" },
  { name: "Roya de la hoja",      type: "Enfermedad", field: "Potrero Oeste", crop: "Trigo",   risk: 71, level: "high",   trend: "up",   action: "Fungicida en encañado" },
  { name: "Rama negra",           type: "Maleza",     field: "Media Loma",    crop: "Sorgo",   risk: 66, level: "high",   trend: "up",   action: "Control post-emergente" },
];

// Zonas de humedad del lote activo (Lote Norte)
const ZONES = [
  { id: "A1", moisture: 72, stress: 8,  rec: 0,  status: "ok"  },
  { id: "A2", moisture: 64, stress: 14, rec: 6,  status: "ok"  },
  { id: "A3", moisture: 41, stress: 38, rec: 18, status: "dry" },
  { id: "B1", moisture: 58, stress: 19, rec: 9,  status: "ok"  },
  { id: "B2", moisture: 34, stress: 47, rec: 22, status: "dry" },
  { id: "B3", moisture: 69, stress: 11, rec: 4,  status: "ok"  },
  { id: "C1", moisture: 78, stress: 5,  rec: 0,  status: "wet" },
  { id: "C2", moisture: 52, stress: 24, rec: 12, status: "ok"  },
  { id: "C3", moisture: 29, stress: 53, rec: 26, status: "dry" },
];

// Inventario — grano + insumos
const HARVEST = [
  { crop: "Soja",    amount: 420, cap: 800,  unit: "t", value: 168000 },
  { crop: "Maíz",    amount: 980, cap: 1500, unit: "t", value: 176400 },
  { crop: "Trigo",   amount: 210, cap: 400,  unit: "t", value: 54600 },
  { crop: "Girasol", amount: 95,  cap: 200,  unit: "t", value: 38000 },
];
const INPUTS = [
  { name: "Urea 46-0-0",         stock: 58, unit: "% del silo",   reorder: 25, level: "ok"  },
  { name: "Semilla — Soja DM",   stock: 42, unit: "% del silo",   reorder: 20, level: "ok"  },
  { name: "Gasoil",              stock: 19, unit: "% del tanque", reorder: 25, level: "low" },
  { name: "Presupuesto de agua", stock: 44, unit: "% restante",   reorder: 20, level: "ok"  },
];

const PRODUCTIVITY = [
  { tier: "Alta",  pct: 44, color: "#4f8a2f" },
  { tier: "Media", pct: 36, color: "#c6cf4a" },
  { tier: "Baja",  pct: 20, color: "#cf9b4a" },
];

const NDVI_HISTORY = [0.18, 0.24, 0.32, 0.41, 0.50, 0.56, 0.60, 0.63, 0.64, 0.62, 0.61, 0.60];
const YIELD_FORECAST = [
  { label: "Optimista", data: [2.4, 2.8, 3.1, 3.4, 3.6, 3.7, 3.8, 3.9, 4.0, 4.0, 4.1, 4.1] },
  { label: "Esperado",  data: [2.2, 2.5, 2.8, 3.0, 3.2, 3.4, 3.5, 3.6, 3.7, 3.7, 3.8, 3.8] },
  { label: "Bajo",      data: [1.9, 2.1, 2.3, 2.5, 2.6, 2.7, 2.8, 2.9, 2.9, 3.0, 3.0, 3.0] },
];

// Agroquímicos — almacén + dosis/ha de referencia (demo; verificar marbete)
// pricePerUnit en USD/L (o USD/kg urea) — ilustrativo para costo/ha
const CHEMICALS = [
  { name: "Azoxistrobina + Cipro.", brand: "Amistar Top",  type: "Fungicida",    stock: 80, unit: "L",  rateHa: 0.5,  pricePerUnit: 28, phi: 14, rei: 12, target: "Roya / manchas" },
  { name: "Clorantraniliprol",      brand: "Coragen",      type: "Insecticida",  stock: 25, unit: "L",  rateHa: 0.1,  pricePerUnit: 95, phi: 14, rei: 12, target: "Isoca / cogollero" },
  { name: "Lambda-cialotrina",      brand: "Karate Zeon",  type: "Insecticida",  stock: 40, unit: "L",  rateHa: 0.08, pricePerUnit: 22, phi: 21, rei: 24, target: "Chinche / defoliadoras" },
  { name: "Glifosato 66,2%",        brand: "Roundup Full", type: "Herbicida",    stock: 200, unit: "L", rateHa: 2.5,  pricePerUnit: 4.5, phi: 0,  rei: 12, target: "Barbecho / malezas" },
  { name: "2,4-D",                  brand: "DMA 6",        type: "Herbicida",    stock: 90, unit: "L",  rateHa: 0.6,  pricePerUnit: 6,  phi: 0,  rei: 24, target: "Hoja ancha" },
  { name: "Urea 46-0-0",            brand: "Urea 46-0-0",  type: "Fertilizante", stock: 12000, unit: "kg", rateHa: 120, pricePerUnit: 0.45, phi: 0, rei: 0, target: "Nitrógeno" },
];
const CHEM_TYPE = {
  Fungicida:    "#3f7fb0",
  Herbicida:    "#b58a16",
  Insecticida:  "#c0492f",
  Fertilizante: "#4f8a2f",
};
const APPLICATIONS = [
  { date: "06 jul", product: "Amistar Top",  type: "Fungicida",    field: "Potrero Oeste", rate: "0,5 L/ha",  area: 125, status: "scheduled" },
  { date: "04 jul", product: "Urea 46-0-0",  type: "Fertilizante", field: "Lote Sur",      rate: "120 kg/ha", area: 280, status: "applied" },
  { date: "02 jul", product: "Coragen",      type: "Insecticida",  field: "Lote Norte",    rate: "0,1 L/ha",  area: 320, status: "applied" },
  { date: "28 jun", product: "Karate Zeon",  type: "Insecticida",  field: "Lote Este",     rate: "0,08 L/ha", area: 95,  status: "applied" },
  { date: "20 jun", product: "Roundup Full", type: "Herbicida",    field: "Media Loma",    rate: "2,5 L/ha",  area: 110, status: "applied" },
];

// Coords demo del establecimiento (Río Segundo, Córdoba) — Open-Meteo
const FARM_COORDS = { lat: -31.4173, lng: -63.2438 };

/** Polígonos [lat, lng] alrededor del casco. Solo para el visor; no son mensura. */
(function attachFieldGeometry() {
  const { lat, lng } = FARM_COORDS;
  const toLL = (nKm, eKm) => [
    lat + nKm / 110.574,
    lng + eKm / (111.32 * Math.cos((lat * Math.PI) / 180)),
  ];
  const rect = (n0, e0, n1, e1) => {
    const ring = [toLL(n0, e0), toLL(n0, e1), toLL(n1, e1), toLL(n1, e0)];
    ring.push(ring[0]);
    return { coordinates: ring, center: toLL((n0 + n1) / 2, (e0 + e1) / 2) };
  };
  const geo = {
    "F-01": rect(0.30, -0.10, 1.95, 1.80),
    "F-05": rect(-0.85, -0.10, 0.30, 1.80),
    "F-04": rect(-2.15, 0.75, -0.85, 1.80),
    "F-06": rect(-2.15, -0.10, -0.85, 0.75),
    "F-08": rect(1.20, -2.15, 1.95, -0.20),
    "F-03": rect(0.15, -2.15, 1.20, -0.20),
    "F-07": rect(-0.95, -2.15, 0.15, -0.20),
    "F-02": rect(-2.15, -2.15, -0.95, -0.20),
  };
  (typeof FIELDS !== "undefined" ? FIELDS : []).forEach((f) => {
    if (geo[f.id]) Object.assign(f, geo[f.id]);
  });
})();
const PHI_ACTIVE = [
  { field: "Lote Norte",    product: "Coragen",     elapsed: 5, phi: 14 },
  { field: "Lote Este",     product: "Karate Zeon", elapsed: 9, phi: 21 },
];
const SPRAY_RECS = [
  { threat: "Roya de la hoja", field: "Potrero Oeste", product: "Amistar Top", rate: "0,5 L/ha",  phi: 14, level: "high" },
  { threat: "Roya asiática",   field: "Lote Este",     product: "Amistar Top", rate: "0,5 L/ha",  phi: 14, level: "high" },
  { threat: "Isoca medidora",  field: "Lote Norte",    product: "Coragen",     rate: "0,1 L/ha",  phi: 14, level: "medium" },
];

const AI_INSIGHTS = {
  dashboard:  { tag: "Campaña", text: "La campaña va bien en Lote Norte (soja NDVI 0,72). Lote Este y Media Loma arrastran el promedio por estrés hídrico — recuperar esos lotes suma más que empujar los ya sanos.", action: "Abrir plan de recuperación" },
  fields:     { tag: "Aptitud del lote", text: "Lote Norte está en zona óptima para soja de primera: NDVI estable y humedad adecuada. Priorizá el monitoreo de isoca y chinche en R3–R5.", action: "Ver detalles" },
  irrigation: { tag: "Humedad", text: "Zonas B2 y C3 del Lote Norte están bajo 35% de humedad. Si hay pivote, programá 20–25 mm antes del frente del jueves.", action: "Programar riego" },
  climate:    { tag: "Riesgo climático", text: "El jueves hay alta probabilidad de lluvia (~70%). Retrasá urea y pulverizaciones hasta el viernes/sábado para evitar lavado y deriva.", action: "Ajustar plan" },
  pests:      { tag: "Fitosanitario", text: "Roya de la hoja en Potrero Oeste (trigo) al 71% y roya asiática en Lote Este (soja) al 78%. Ventana de fungicida si el umbral se confirma en campo.", action: "Crear tarea" },
  reports:    { tag: "Productividad", text: "El 20% del área está en baja productividad, concentrada en Media Loma y Lote Este. Un mapa VRA o ajuste de stand puede recuperar 0,4–0,8 t/ha en esos ambientes.", action: "Crear mapa VRA" },
  chemicals:  { tag: "Pulverización", text: "Roya en trigo (Potrero Oeste) amerita fungicida protectante/curativo. Programá aplicación con viento <15 km/h y sin lluvia en 6 h — carencia 14 días.", action: "Programar pulverización" },
};

const FIELD_INFO = {
  "F-01": { variety: "Soja DM 46R3 STS", plantedOn: "15 nov 2025", stage: "R3 · Inicio de vainas", harvestEta: "20 abr 2026", soil: "Franco limoso", density: "32 pl/m²", lastIrrigation: "Secano", lastSpray: "Coragen · 02 jul", obs: "Dosel uniforme. Monitorear isoca y chinche.", ndviTrend: [0.48, 0.55, 0.62, 0.67, 0.70, 0.72] },
  "F-02": { variety: "Maíz DK 72-10 VT3P", plantedOn: "28 sep 2025", stage: "R3 · Grano lechoso", harvestEta: "15 mar 2026", soil: "Franco arcilloso", density: "74.000 pl/ha", lastIrrigation: "Secano · 6 días", lastSpray: "Urea · 04 jul", obs: "Humedad media. Vigilar cogollero residual y roya.", ndviTrend: [0.52, 0.56, 0.59, 0.60, 0.61, 0.61] },
  "F-03": { variety: "Trigo Baguette 620", plantedOn: "20 jun 2026", stage: "Encañado (Z32)", harvestEta: "05 dic 2026", soil: "Franco", density: "300 pl/m²", lastIrrigation: "Secano", lastSpray: "—", obs: "Buen macollaje. Riesgo de roya en alza con lluvias.", ndviTrend: [0.40, 0.48, 0.53, 0.56, 0.57, 0.58] },
  "F-04": { variety: "Soja DM 40R16", plantedOn: "22 nov 2025", stage: "R2 · Floración plena", harvestEta: "25 abr 2026", soil: "Franco arenoso", density: "30 pl/m²", lastIrrigation: "Sin riego · 10 días", lastSpray: "Karate · 28 jun", obs: "Estrés hídrico + roya. Prioridad máxima de manejo.", ndviTrend: [0.58, 0.54, 0.50, 0.48, 0.46, 0.45] },
  "F-05": { variety: "Maíz AX 7784 VT3P", plantedOn: "05 oct 2025", stage: "R4 · Grano pastoso", harvestEta: "20 mar 2026", soil: "Franco limoso", density: "76.000 pl/ha", lastIrrigation: "Pivote · 01 jul · 22 mm", lastSpray: "—", obs: "Mejor maíz del campo. Sin alertas activas.", ndviTrend: [0.50, 0.56, 0.61, 0.65, 0.67, 0.68] },
  "F-06": { variety: "Girasol ADV 5505 CL", plantedOn: "10 oct 2025", stage: "R6 · Fin floración", harvestEta: "28 feb 2026", soil: "Franco", density: "55.000 pl/ha", lastIrrigation: "Secano", lastSpray: "—", obs: "Stand bueno. Sequía de llenado es el riesgo residual.", ndviTrend: [0.50, 0.55, 0.59, 0.62, 0.63, 0.64] },
  "F-07": { variety: "Sorgo Pioneer 84G62", plantedOn: "15 nov 2025", stage: "Floración", harvestEta: "10 abr 2026", soil: "Franco arcilloso", density: "160.000 pl/ha", lastIrrigation: "Sin riego · 12 días", lastSpray: "Roundup · 20 jun", obs: "NDVI crítico 0,38 + rama negra. Estrés severo.", ndviTrend: [0.50, 0.47, 0.44, 0.41, 0.39, 0.38] },
  "F-08": { variety: "Alfalfa Victoria SP", plantedOn: "Establecida 2024", stage: "Corte 3 — rebrote", harvestEta: "Corte: 28 jul 2026", soil: "Franco", density: "—", lastIrrigation: "06 jul · 16 mm", lastSpray: "—", obs: "Mejor lote forrajero. NDVI 0,74.", ndviTrend: [0.66, 0.69, 0.71, 0.73, 0.74, 0.74] },
};

const HARVEST_INFO = {
  "Soja": {
    silo: "Silo A-1", grade: "Cámara AR", avgMoisture: 12.8, target: 13.5,
    harvestStart: "15 abr 2026", harvestEnd: "—", destination: "Acopio Rosario", pricePerT: 400,
    note: "Humedad apta para entrega. Proteína y aceite a confirmar en acopio.",
    entries: [
      { date: "05 jul", field: "Lote Norte", tonnes: 180, moisture: 12.6 },
      { date: "28 jun", field: "Lote Este", tonnes: 90, moisture: 13.1 },
    ],
  },
  "Maíz": {
    silo: "Silo B-2", grade: "Grado 2", avgMoisture: 14.2, target: 14.5,
    harvestStart: "10 mar 2026", harvestEnd: "—", destination: "Export / feedlot", pricePerT: 180,
    note: "Humedad dentro de rango de almacenaje. Apto para entrega.",
    entries: [
      { date: "03 jul", field: "Campo Central", tonnes: 420, moisture: 14.0 },
      { date: "20 jun", field: "Lote Sur", tonnes: 310, moisture: 14.5 },
    ],
  },
  "Trigo": {
    silo: "Silo C-1", grade: "Panadero", avgMoisture: 12.5, target: 13.5,
    harvestStart: "—", harvestEnd: "—", destination: "Molino regional", pricePerT: 260,
    note: "Campaña fina en curso — aún sin ingreso mayor.",
    entries: [],
  },
  "Girasol": {
    silo: "Silo D-1", grade: "Aceitero", avgMoisture: 9.5, target: 11,
    harvestStart: "—", harvestEnd: "—", destination: "Aceitera", pricePerT: 400,
    note: "Cosecha estimada fin de febrero.",
    entries: [],
  },
};

// Attach NDVI series onto fields for satellite engine
FIELDS.forEach((f) => {
  const info = FIELD_INFO[f.id];
  if (info && info.ndviTrend) {
    f.ndviTrend = info.ndviTrend;
    f.lastSceneDate = "2026-07-05";
    f.ndviSource = "Sentinel-2 (demo)";
  }
});

Object.assign(window, {
  FARM, FARM_COORDS, FIELDS, STATUS, WEATHER, PESTS, ZONES, HARVEST, INPUTS, PRODUCTIVITY,
  NDVI_HISTORY, YIELD_FORECAST, AI_INSIGHTS, CHEMICALS, CHEM_TYPE, APPLICATIONS,
  PHI_ACTIVE, SPRAY_RECS, FIELD_INFO, HARVEST_INFO,
});
