/* global React, Icons */
/* Capa interactiva: avisos (toasts), Agrónomo IA (chat real con Claude) y utilidades. */
const { useState: iState, useEffect: iEffect, useRef: iRef } = React;

/* ---------------- Avisos / Toasts (DOM directo, fuera del canvas escalado) ---------------- */
(function () {
  let host;
  function ensure() {
    if (!host) {
      host = document.createElement("div");
      host.style.cssText =
        "position:fixed;left:50%;bottom:30px;transform:translateX(-50%);z-index:99999;" +
        "display:flex;flex-direction:column;gap:10px;align-items:center;pointer-events:none;font-family:Onest,system-ui,sans-serif;";
      document.body.appendChild(host);
    }
    return host;
  }
  const ICONS = {
    ok: '<path d="M4 12l5 5L20 6"/>',
    info: '<path d="M12 8h.01M11 12h1v5h1"/>',
    warn: '<path d="M12 3 2 20h20L12 3ZM12 9v5M12 17h.01"/>',
  };
  window.toast = function (msg, kind) {
    kind = kind || "ok";
    const h = ensure();
    const t = document.createElement("div");
    t.style.cssText =
      "pointer-events:auto;display:flex;align-items:center;gap:11px;background:#2d3122;color:#f2f3ea;" +
      "padding:13px 18px 13px 15px;border-radius:14px;font-size:14.5px;font-weight:500;letter-spacing:-0.01em;" +
      "box-shadow:0 18px 40px -16px rgba(20,30,10,0.6);max-width:440px;opacity:0;transform:translateY(14px);" +
      "transition:opacity .28s ease, transform .28s ease;border:1px solid rgba(255,255,255,0.06);";
    const accent = kind === "warn" ? "#e0b341" : kind === "info" ? "#9fc0e6" : "#c6e84b";
    t.innerHTML =
      '<span style="width:26px;height:26px;border-radius:8px;flex:none;background:' +
      accent +
      ';color:#1b1e14;display:flex;align-items:center;justify-content:center;">' +
      '<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.2" stroke-linecap="round" stroke-linejoin="round">' +
      (ICONS[kind] || ICONS.ok) +
      "</svg></span><span>" +
      msg +
      "</span>";
    h.appendChild(t);
    requestAnimationFrame(() => {
      t.style.opacity = "1";
      t.style.transform = "translateY(0)";
    });
    setTimeout(() => {
      t.style.opacity = "0";
      t.style.transform = "translateY(14px)";
      setTimeout(() => t.remove(), 320);
    }, 3000);
  };
})();

/* ---------------- Estado global ligero (no leídos) ---------------- */
window.HARV = {
  getUnread() {
    const v = localStorage.getItem("harvesta_unread");
    return v == null ? 3 : +v;
  },
  setUnread(n) {
    localStorage.setItem("harvesta_unread", String(n));
    window.dispatchEvent(new CustomEvent("harvesta:unread", { detail: n }));
  },
};

/* Abrir el Agrónomo IA desde cualquier botón */
window.askAI = (seed) =>
  window.dispatchEvent(new CustomEvent("assistant:open", { detail: { seed: seed || "" } }));

/* ---------------- Agrónomo IA (chat) ---------------- */
/** Contexto estructurado para /api/agent (sistema + demo). */
function buildFarmContext() {
  const f = window.FARM || {};
  const fields = window.FIELDS || [];
  const pests = window.PESTS || [];
  const weather = window.WEATHER || [];
  const chemicals = window.CHEMICALS || [];
  const sprayRecs = window.SPRAY_RECS || [];
  const eng = window.CampoEngine;

  const fieldPayload = fields.map((x) => ({
    id: x.id,
    name: x.name,
    crop: x.crop,
    zone: x.zone,
    area_ha: x.area,
    ndvi: x.ndvi,
    moisture: x.moisture,
    status: window.STATUS?.[x.status]?.label || x.status,
    yieldPred: x.yieldPred,
    unit: x.unit,
    ndviTrend: x.ndviTrend,
    lastSceneDate: x.lastSceneDate,
    ndviSource: x.ndviSource,
  }));

  // Client-side precompute (also re-run server-side)
  let sprayWindow = null;
  let ndviAnalysis = null;
  let prescriptions = null;
  let valueProp = null;
  if (eng) {
    sprayWindow = eng.computeSprayWindow(
      weather.map((w) => ({
        day: w.day,
        // WEATHER.rain is % probability in demo UI — map to mm proxy
        rain: w.rain >= 60 ? 14 : w.rain >= 30 ? 6 : w.rain >= 10 ? 2 : 0,
        wind: w.wind,
        t: w.t,
        lo: w.lo,
      }))
    );
    ndviAnalysis = eng.analyzeAllFieldsNdvi(fieldPayload);
    prescriptions = eng
      .buildPrescriptionsFromCatalog({
        sprayRecs,
        chemicals,
        fields: fieldPayload.map((f) => ({ name: f.name, area: f.area_ha })),
      })
      .filter((p) => p.ok);
    valueProp = eng.valueProposition({
      cultivated_ha: f.cultivated,
      fieldsCount: f.fieldsCount,
    });
  }

  // Live spray window if fetched
  if (window.__SPRAY_WINDOW) sprayWindow = window.__SPRAY_WINDOW;

  return {
    name: f.name,
    location: f.location,
    coords: f.coords,
    season: f.season,
    cultivated_ha: f.cultivated,
    fieldsCount: f.fieldsCount,
    avgNDVI: f.avgNDVI,
    predictedYield_t: f.predictedYield,
    yieldConfidence: f.yieldConfidence,
    alerts: f.alerts,
    lat: window.FARM_COORDS?.lat,
    lng: window.FARM_COORDS?.lng,
    fields: fieldPayload,
    pests: pests.map((p) => ({
      name: p.name,
      type: p.type,
      field: p.field,
      crop: p.crop,
      risk: p.risk,
      level: p.level,
      action: p.action,
    })),
    weather: weather.map((w) => ({
      day: w.day,
      t: w.t,
      lo: w.lo,
      cond: w.cond,
      rain: w.rain,
      rainMm: w.rain >= 60 ? 14 : w.rain >= 30 ? 6 : w.rain >= 10 ? 2 : 0,
      wind: w.wind,
    })),
    chemicals: chemicals.map((c) => ({
      name: c.name,
      brand: c.brand,
      type: c.type,
      stock: c.stock,
      unit: c.unit,
      rateHa: c.rateHa,
      pricePerUnit: c.pricePerUnit,
      phi: c.phi,
      rei: c.rei,
      target: c.target,
    })),
    sprayRecs,
    sprayWindow,
    ndviAnalysis,
    prescriptions,
    valueProp,
    visorSoil: window.__VISOR_SOIL || null,
    applicationSlot: window.__APPLY_SLOT || null,
    fleet: window.__JD_FLEET
      ? {
          connected: !!window.__JD_FLEET.connected,
          demo: !!window.__JD_FLEET.demo,
          machines: (window.__JD_FLEET.equipment || []).map((m) => ({
            id: m.id,
            name: m.name,
            model: m.model,
            category: m.category,
          })),
        }
      : null,
  };
}

const SUGERENCIAS = [
  "Dosis/ha para la roya en trigo",
  "¿Qué dice el NDVI satelital?",
  "Ventana de pulverización esta semana",
  "¿Cuánto valor genera PampaGo en mi campo?",
];

function fallbackReply(text) {
  const t = (text || "").toLowerCase();
  if (/(riego|agua|humedad|seco)/.test(t))
    return "Las zonas B2 (34%) y C3 (29%) del Lote Norte están bajo el umbral. Aplicá 20–25 mm en las próximas 24 h si hay pivote, antes del frente de lluvia del jueves.";
  if (/(plaga|enfermedad|roya|isoca|hongo|chinche)/.test(t))
    return "El riesgo más alto es roya asiática en Lote Este (78%) y roya de la hoja en Potrero Oeste (71%). Monitoreá umbral y programá fungicida con viento bajo.";
  if (/(rendimiento|producción|cosecha|rinde)/.test(t))
    return "Lote Este (soja) y Media Loma (sorgo) arrastran el promedio por estrés hídrico. Corrigiendo humedad y malezas ahí recuperás más toneladas que empujando los lotes ya sanos.";
  if (/(clima|lluvia|jueves|tiempo|helada)/.test(t))
    return "El jueves hay ~70% de probabilidad de lluvia. Retrasá urea y pulverizaciones hasta el viernes/sábado para evitar lavado y deriva.";
  return "Estoy acá para ayudarte con riego, plagas, clima, rinde e insumos. Decime qué lote o tema te preocupa y te doy una recomendación concreta.";
}

/** Llama al Agrónomo IA (Vercel /api/agent). Fallback local si falla la red. */
async function callAgronomoAPI(userText, history) {
  const farmContext = buildFarmContext();
  const messages = history
    .filter((m) => !m.intro && (m.role === "user" || m.role === "assistant"))
    .map((m) => ({ role: m.role, content: m.content }));
  // Asegurar que el último turno del usuario esté incluido
  if (!messages.length || messages[messages.length - 1].content !== userText) {
    messages.push({ role: "user", content: userText });
  }

  // Compat: entorno Claude artifacts
  if (window.claude && window.claude.complete) {
    const ctx =
      "Contexto del establecimiento:\n" +
      JSON.stringify(farmContext, null, 2) +
      "\n\nRespondé en español argentino como Agrónomo IA de PampaGo Campo.";
    const api = messages.map((m, i) =>
      i === 0 && m.role === "user"
        ? { role: "user", content: ctx + "\n\nCONSULTA:\n" + m.content }
        : m
    );
    const reply = await window.claude.complete({ messages: api });
    if (reply && String(reply).trim()) return String(reply).trim();
  }

  const res = await fetch("/api/agent", {
    method: "POST",
    headers: { "Content-Type": "application/json" },
    body: JSON.stringify({ messages, farmContext }),
  });
  if (!res.ok) throw new Error("API " + res.status);
  const data = await res.json();
  if (data.reply && String(data.reply).trim()) return String(data.reply).trim();
  throw new Error("Respuesta vacía");
}

function renderBold(text, keyBase) {
  return String(text).split(/(\*\*[^*]+\*\*|\*[^*]+\*)/g).map((part, i) => {
    if (part.startsWith("**") && part.endsWith("**")) return <strong key={keyBase + "-" + i}>{part.slice(2, -2)}</strong>;
    if (part.startsWith("*") && part.endsWith("*") && part.length > 2) return <strong key={keyBase + "-" + i}>{part.slice(1, -1)}</strong>;
    return <React.Fragment key={keyBase + "-" + i}>{part}</React.Fragment>;
  });
}

function renderRich(text) {
  // Limpia markdown ligero (encabezados, viñetas) y aplica negritas.
  const lines = String(text).replace(/\r/g, "").split("\n");
  return lines.map((ln, i) => {
    let l = ln.replace(/^#{1,6}\s+/, "");
    l = l.replace(/^\s*[-*]\s+/, "•  ");
    return (
      <React.Fragment key={i}>
        {renderBold(l, i)}
        {i < lines.length - 1 ? "\n" : null}
      </React.Fragment>
    );
  });
}

function Typing() {
  return (
    <div style={{ display: "flex", gap: 5, alignItems: "center", padding: "4px 2px" }}>
      {[0, 1, 2].map((i) => (
        <span
          key={i}
          style={{
            width: 7, height: 7, borderRadius: 999, background: "#9aa07f",
            animation: "harvBounce 1s infinite ease-in-out", animationDelay: i * 0.16 + "s",
          }}
        />
      ))}
    </div>
  );
}

function AIAgronomo() {
  const farmName = (window.FARM && window.FARM.name) || "tu establecimiento";
  const intro = {
    role: "assistant",
    intro: true,
    content:
      "¡Hola! Soy tu **Agrónomo IA** de PampaGo Campo. Tengo los datos de " +
      farmName +
      " al día: lotes, NDVI, clima y plagas. Puedo ayudarte con ventanas de pulverización, riego, fitosanitarios y rinde. ¿En qué te ayudo?",
  };
  const [open, setOpen] = iState(false);
  const [msgs, setMsgs] = iState([intro]);
  const [input, setInput] = iState("");
  const [busy, setBusy] = iState(false);
  const msgsRef = iRef([intro]);
  const busyRef = iRef(false);
  const scroller = iRef(null);
  const inputRef = iRef(null);

  const sync = (arr) => {
    msgsRef.current = arr;
    setMsgs(arr);
  };

  async function send(raw) {
    const text = (raw == null ? input : raw).trim();
    if (!text || busyRef.current) return;
    const next = [...msgsRef.current, { role: "user", content: text }];
    sync(next);
    setInput("");
    setBusy(true);
    busyRef.current = true;
    try {
      const reply = await callAgronomoAPI(text, next);
      sync([...msgsRef.current, { role: "assistant", content: reply }]);
    } catch (e) {
      sync([
        ...msgsRef.current,
        { role: "assistant", content: fallbackReply(text) },
      ]);
    }
    setBusy(false);
    busyRef.current = false;
  }

  iEffect(() => {
    const onOpen = (e) => {
      setOpen(true);
      const seed = e.detail && e.detail.seed;
      if (seed) setTimeout(() => send(seed), 220);
      else setTimeout(() => inputRef.current && inputRef.current.focus(), 280);
    };
    window.addEventListener("assistant:open", onOpen);
    const onKey = (e) => { if (e.key === "Escape") setOpen(false); };
    window.addEventListener("keydown", onKey);
    return () => {
      window.removeEventListener("assistant:open", onOpen);
      window.removeEventListener("keydown", onKey);
    };
  }, []);

  iEffect(() => {
    if (scroller.current) scroller.current.scrollTop = scroller.current.scrollHeight;
  }, [msgs, busy, open]);

  const showChips = msgs.filter((m) => m.role === "user").length === 0;

  return (
    <React.Fragment>
      {/* Lanzador flotante */}
      {!open && (
        <button
          onClick={() => setOpen(true)}
          title="Agrónomo IA"
          style={{
            position: "absolute", right: 26, bottom: 26, zIndex: 40, width: 60, height: 60, borderRadius: 999,
            background: "var(--lime)", color: "var(--ink)", border: "none", cursor: "pointer",
            display: "flex", alignItems: "center", justifyContent: "center",
            boxShadow: "0 16px 34px -12px rgba(150,180,30,0.95)",
          }}
        >
          <Icons.spark size={26} />
        </button>
      )}

      {open && (
        <div style={{ position: "absolute", inset: 0, zIndex: 50 }}>
          <div
            onClick={() => setOpen(false)}
            style={{ position: "absolute", inset: 0, background: "rgba(20,28,10,0.34)", backdropFilter: "blur(2px)" }}
          />
          <div
            style={{
              position: "absolute", right: 0, top: 0, width: 432, height: 940, background: "var(--cream)",
              boxShadow: "-30px 0 70px -30px rgba(30,40,15,0.6)", display: "flex", flexDirection: "column",
              animation: "harvSlide .32s cubic-bezier(.2,.8,.2,1)",
            }}
          >
            {/* Encabezado */}
            <div style={{ background: "var(--olive-dark)", color: "#f2f3ea", padding: "20px 20px 18px", position: "relative", overflow: "hidden" }}>
              <div style={{ position: "absolute", right: -24, top: -28, width: 130, height: 130, borderRadius: 999, background: "radial-gradient(circle, rgba(198,232,75,0.26), transparent 70%)" }} />
              <div style={{ display: "flex", alignItems: "center", gap: 12 }}>
                <div style={{ width: 40, height: 40, borderRadius: 12, background: "var(--lime)", color: "var(--ink)", display: "flex", alignItems: "center", justifyContent: "center", flex: "none" }}>
                  <Icons.spark size={22} />
                </div>
                <div style={{ lineHeight: 1.25, flex: 1 }}>
                  <div style={{ fontSize: 16, fontWeight: 700 }}>Agrónomo IA</div>
                  <div style={{ fontSize: 12, color: "var(--lime)", fontWeight: 600, display: "flex", alignItems: "center", gap: 6 }}>
                    <span style={{ width: 7, height: 7, borderRadius: 999, background: "#c6e84b" }} /> En línea · {(window.FARM && window.FARM.name) || "PampaGo"}
                  </div>
                </div>
                <button onClick={() => setOpen(false)} style={{ width: 34, height: 34, borderRadius: 10, border: "none", background: "rgba(255,255,255,0.12)", color: "#f2f3ea", cursor: "pointer", display: "flex", alignItems: "center", justifyContent: "center" }}>
                  <Icons.close size={18} />
                </button>
              </div>
            </div>

            {/* Mensajes */}
            <div ref={scroller} style={{ flex: 1, overflowY: "auto", padding: "20px 18px", display: "flex", flexDirection: "column", gap: 14, background: "#eceee4" }}>
              {msgs.map((m, i) => (
                <div key={i} style={{ display: "flex", justifyContent: m.role === "user" ? "flex-end" : "flex-start" }}>
                  <div
                    style={{
                      maxWidth: "84%", padding: "12px 15px", borderRadius: 16, fontSize: 14, lineHeight: 1.5,
                      whiteSpace: "pre-wrap",
                      background: m.role === "user" ? "var(--lime)" : "var(--cream)",
                      color: "var(--ink)",
                      borderBottomRightRadius: m.role === "user" ? 5 : 16,
                      borderBottomLeftRadius: m.role === "user" ? 16 : 5,
                      boxShadow: "var(--shadow-soft)",
                    }}
                  >
                    {renderRich(m.content)}
                  </div>
                </div>
              ))}
              {busy && (
                <div style={{ display: "flex", justifyContent: "flex-start" }}>
                  <div style={{ padding: "10px 15px", borderRadius: 16, borderBottomLeftRadius: 5, background: "var(--cream)", boxShadow: "var(--shadow-soft)" }}>
                    <Typing />
                  </div>
                </div>
              )}
              {showChips && (
                <div style={{ display: "flex", flexWrap: "wrap", gap: 8, marginTop: 4 }}>
                  {SUGERENCIAS.map((s) => (
                    <button
                      key={s}
                      onClick={() => send(s)}
                      style={{ border: "1px solid rgba(0,0,0,0.08)", background: "var(--cream)", color: "var(--ink-2)", fontFamily: "Onest", fontSize: 13, fontWeight: 500, padding: "9px 13px", borderRadius: 999, cursor: "pointer", textAlign: "left" }}
                    >
                      {s}
                    </button>
                  ))}
                </div>
              )}
            </div>

            {/* Entrada */}
            <div style={{ padding: "14px 16px 18px", background: "var(--cream)", borderTop: "1px solid rgba(0,0,0,0.06)" }}>
              <div style={{ display: "flex", alignItems: "center", gap: 8, background: "#eceee4", borderRadius: 999, padding: "6px 6px 6px 16px" }}>
                <input
                  ref={inputRef}
                  value={input}
                  onChange={(e) => setInput(e.target.value)}
                  onKeyDown={(e) => { if (e.key === "Enter") send(); }}
                  placeholder="Escribe tu consulta…"
                  style={{ flex: 1, border: "none", background: "transparent", outline: "none", fontFamily: "Onest", fontSize: 14.5, color: "var(--ink)" }}
                />
                <button
                  onClick={() => send()}
                  disabled={busy}
                  className="btn-lime"
                  style={{ width: 42, height: 42, borderRadius: 999, display: "flex", alignItems: "center", justifyContent: "center", flex: "none", opacity: busy ? 0.6 : 1 }}
                >
                  <Icons.send size={19} />
                </button>
              </div>
              <div style={{ fontSize: 11, color: "var(--muted)", textAlign: "center", marginTop: 9 }}>
                El Agrónomo IA puede equivocarse. Validá dosis y marbetes SENASA con tu ingeniero.
              </div>
            </div>
          </div>
        </div>
      )}
    </React.Fragment>
  );
}

window.AIAgronomo = AIAgronomo;
