/* global React, Icons, FIELDS, WEATHER, PESTS, ZONES, AI_INSIGHTS, FARM_COORDS, Card, KPI, AIInsight, Topbar, LineChart, BarsH, BarsV, Gauge, Page, CampoEngine */
const { useState: oState, useEffect: oEffect } = React;

const LEVEL = {
  high:   { label: "Alta",  color: "#c0492f", bg: "rgba(200,90,60,0.14)" },
  medium: { label: "Media", color: "#b58a16", bg: "rgba(214,170,40,0.16)" },
  low:    { label: "Baja",  color: "#4f8a2f", bg: "rgba(123,180,60,0.15)" },
};
const LevelBadge = ({ level }) => {
  const l = LEVEL[level];
  return <span style={{ fontSize: 12, fontWeight: 700, color: l.color, background: l.bg, padding: "3px 10px", borderRadius: 999 }}>{l.label}</span>;
};
const moistColor = (m) => m >= 65 ? "#3a6b22" : m >= 50 ? "#6f9a3a" : m >= 40 ? "#c6a93a" : "#cf7a3a";
const Trend = ({ t }) => t === "up" ? <Icons.trendUp size={15} /> : t === "down" ? <Icons.trendDown size={15} /> : <span style={{ color: "var(--muted)" }}>—</span>;

/* ---------------- RIEGO ---------------- */
function ZoneGrid() {
  return (
    <Card title="Humedad por zona" sub="Lote Norte · 9 zonas de manejo"
      action={<div style={{ display: "flex", gap: 12, fontSize: 11.5, color: "var(--muted)" }}>
        <span style={{ display: "flex", alignItems: "center", gap: 5 }}><span style={{ width: 9, height: 9, borderRadius: 3, background: "#cf7a3a" }} />Seca</span>
        <span style={{ display: "flex", alignItems: "center", gap: 5 }}><span style={{ width: 9, height: 9, borderRadius: 3, background: "#3a6b22" }} />Óptima</span>
      </div>}>
      <div style={{ display: "grid", gridTemplateColumns: "repeat(3,1fr)", gap: 8 }}>
        {ZONES.map((z) => (
          <div key={z.id} onClick={() => z.rec > 0 ? window.toast(`Riego de ${z.rec} mm programado para Zona ${z.id}`) : window.toast(`Zona ${z.id} en humedad óptima`, "info")}
            style={{ borderRadius: 12, background: moistColor(z.moisture), color: "#fff", padding: "14px 14px", cursor: "pointer",
            position: "relative", minHeight: 86, display: "flex", flexDirection: "column", justifyContent: "space-between" }}>
            <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center" }}>
              <span style={{ fontSize: 12.5, fontWeight: 700, opacity: 0.9 }}>{z.id}</span>
              {z.rec > 0 && <span style={{ fontSize: 10.5, fontWeight: 700, background: "rgba(255,255,255,0.2)", padding: "2px 7px", borderRadius: 999 }}>+{z.rec}mm</span>}
            </div>
            <div>
              <div style={{ fontSize: 24, fontWeight: 800, letterSpacing: "-0.02em" }}>{z.moisture}<span style={{ fontSize: 13 }}>%</span></div>
              <div style={{ fontSize: 11, opacity: 0.82 }}>estrés {z.stress}</div>
            </div>
          </div>
        ))}
      </div>
    </Card>
  );
}

const SCHEDULE = [
  { zone: "Zona B2", mm: 22, when: "Hoy · 18:00", dur: "45 min", status: "queued" },
  { zone: "Zona C3", mm: 26, when: "Hoy · 19:00", dur: "55 min", status: "queued" },
  { zone: "Zona A3", mm: 18, when: "Mañana · 06:00", dur: "38 min", status: "scheduled" },
  { zone: "Zona C2", mm: 12, when: "Mañana · 06:45", dur: "24 min", status: "scheduled" },
];

function IrrigationTab() {
  const [q, setQ] = oState("");
  const query = q.trim().toLowerCase();
  const recs = ZONES.filter((z) => z.rec >= 12).filter((z) => !query || ("zona " + z.id).toLowerCase().includes(query));
  return (
    <Page>
      <Topbar title="Riego" subtitle="Gestión de agua por zona · Lote Norte" range="Próximas 48 horas" onSearch={setQ} searchPlaceholder="Buscar zona…" />
      <div style={{ display: "grid", gridTemplateColumns: "repeat(4,1fr)", gap: 16, marginBottom: 18 }}>
        <KPI icon={Icons.drop} label="Aplicado esta semana" value="148" unit="mm" delta={-8} deltaGood />
        <KPI icon={Icons.gauge} label="Humedad media" value="55" unit="%" delta={-5} />
        <KPI icon={Icons.alert} label="Zonas bajo umbral" value="3" delta={1} deltaGood={false} />
        <KPI icon={Icons.zap} label="Agua ahorrada vs. plan" value="22" unit="%" delta={22} sparkColor="#3f7fb0" />
      </div>
      <div style={{ display: "grid", gridTemplateColumns: "1.5fr 1fr", gap: 18, alignItems: "start" }}>
        <div style={{ display: "flex", flexDirection: "column", gap: 18 }}>
          <ZoneGrid />
          <Card title="Aplicaciones recomendadas" sub="Modelado por IA para evitar estrés hídrico">
            <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr 1fr 1.2fr", gap: 8, fontSize: 11.5, color: "var(--muted)", fontWeight: 600, padding: "0 4px 10px", borderBottom: "1px solid rgba(0,0,0,0.06)" }}>
              <span>ZONA</span><span>HUMEDAD</span><span>RECOMEND.</span><span style={{ textAlign: "right" }}>PRIORIDAD</span>
            </div>
            {recs.map((z) => (
              <div key={z.id} onClick={() => window.toast(`Riego de ${z.rec} mm programado para Zona ${z.id}`)} className="row-hover"
                style={{ display: "grid", gridTemplateColumns: "1fr 1fr 1fr 1.2fr", gap: 8, alignItems: "center", fontSize: 13.5, padding: "11px 4px", borderBottom: "1px solid rgba(0,0,0,0.04)", cursor: "pointer" }}>
                <span style={{ fontWeight: 600 }}>Zona {z.id}</span>
                <span style={{ color: moistColor(z.moisture), fontWeight: 700 }}>{z.moisture}%</span>
                <span style={{ fontWeight: 700 }}>{z.rec} mm</span>
                <div style={{ display: "flex", justifyContent: "flex-end" }}><LevelBadge level={z.stress > 45 ? "high" : "medium"} /></div>
              </div>
            ))}
            {recs.length === 0 && <div style={{ padding: "20px 4px", fontSize: 13.5, color: "var(--muted)" }}>Sin zonas que coincidan.</div>}
          </Card>
        </div>
        <div style={{ display: "flex", flexDirection: "column", gap: 18 }}>
          <AIInsight insight={AI_INSIGHTS.irrigation} />
          <Card title="Presupuesto de agua" sub="Asignación de temporada">
            <Gauge value={36} max={100} label="36%" sub="restante" color="#3f7fb0" size={170} />
            <div style={{ display: "flex", justifyContent: "space-between", fontSize: 13, marginTop: 8 }}>
              <span style={{ color: "var(--muted)" }}>Usado 2.840 m³</span><span style={{ fontWeight: 700 }}>de 4.400 m³</span>
            </div>
          </Card>
          <Card title="Próximo calendario" action={<Icons.clock size={18} />}>
            <div style={{ display: "flex", flexDirection: "column", gap: 12 }}>
              {SCHEDULE.map((s) => (
                <div key={s.zone} onClick={() => window.toast(`${s.zone}: ${s.mm} mm · ${s.when}`, "info")} className="row-hover" style={{ display: "flex", alignItems: "center", gap: 12, padding: "4px 6px", margin: "0 -6px", borderRadius: 10, cursor: "pointer" }}>
                  <div style={{ width: 8, height: 8, borderRadius: 999, background: s.status === "queued" ? "var(--lime-deep)" : "#c9cdb8", flex: "none" }} />
                  <div style={{ flex: 1, minWidth: 0 }}>
                    <div style={{ fontSize: 13.5, fontWeight: 600 }}>{s.zone} · {s.mm} mm</div>
                    <div style={{ fontSize: 12, color: "var(--muted)" }}>{s.when} · {s.dur}</div>
                  </div>
                </div>
              ))}
            </div>
          </Card>
        </div>
      </div>
    </Page>
  );
}

/* ---------------- CLIMA ---------------- */
function SprayWindowPanel() {
  const [spray, setSpray] = oState(null);
  const [live, setLive] = oState(false);
  const [loading, setLoading] = oState(true);

  oEffect(() => {
    const lat = window.FARM_COORDS?.lat ?? -31.4173;
    const lng = window.FARM_COORDS?.lng ?? -63.2438;
    // Demo fallback immediately
    if (window.CampoEngine) {
      const demo = window.CampoEngine.computeSprayWindow(
        WEATHER.map((w) => ({
          day: w.day,
          rain: w.rain >= 60 ? 14 : w.rain >= 30 ? 6 : w.rain >= 10 ? 2 : 0,
          wind: w.wind,
          t: w.t,
          lo: w.lo,
        }))
      );
      setSpray(demo);
      window.__SPRAY_WINDOW = demo;
    }
    setLoading(false);
    // Live Open-Meteo
    fetch(`/api/weather?lat=${lat}&lng=${lng}`)
      .then((r) => r.json())
      .then((d) => {
        if (d.sprayWindow?.days?.length) {
          setSpray(d.sprayWindow);
          window.__SPRAY_WINDOW = d.sprayWindow;
          setLive(!d.demo);
        }
      })
      .catch(() => {});
  }, []);

  const aptColor = (apt) =>
    apt === "apt" ? "#4f8a2f" : apt === "marginal" ? "#b58a16" : "#c0492f";

  return (
    <Card
      title="Ventana de pulverización"
      sub={live ? "Open-Meteo en vivo · Córdoba" : "Modelo local · lluvia + viento + temp"}
      action={
        <button
          onClick={() => window.askAI("Ventana de pulverización esta semana — ¿qué días son aptos y por qué?")}
          className="pill"
          style={{ border: "none", background: "var(--lime)", fontFamily: "Onest", fontWeight: 600, fontSize: 12.5, padding: "7px 12px", cursor: "pointer" }}
        >
          Preguntar IA
        </button>
      }
    >
      {loading && !spray && <div style={{ color: "var(--muted)", fontSize: 13.5 }}>Calculando…</div>}
      {spray && (
        <>
          <div style={{ fontSize: 14, fontWeight: 600, marginBottom: 14, lineHeight: 1.4 }}>
            {spray.aptCount > 0
              ? `${spray.aptCount} día(s) apto(s) · Mejor: ${spray.best?.day || spray.best?.date || "—"} (score ${spray.best?.score})`
              : "Sin día óptimo esta semana — revisá marginales"}
          </div>
          <div style={{ display: "grid", gridTemplateColumns: "repeat(7,1fr)", gap: 8 }}>
            {(spray.days || []).map((d) => (
              <div
                key={d.day + (d.date || "")}
                style={{
                  borderRadius: 12,
                  padding: "10px 6px",
                  textAlign: "center",
                  background: aptColor(d.apt) + "18",
                  border: `1.5px solid ${aptColor(d.apt)}44`,
                  cursor: "default",
                }}
                title={(d.reasons || []).join(" · ")}
              >
                <div style={{ fontSize: 11, fontWeight: 700, color: "var(--muted)" }}>{d.day || d.date}</div>
                <div style={{ fontSize: 13, fontWeight: 800, color: aptColor(d.apt), margin: "6px 0 4px" }}>{d.score}</div>
                <div style={{ fontSize: 10.5, fontWeight: 600, color: aptColor(d.apt) }}>{d.label}</div>
                <div style={{ fontSize: 10, color: "var(--muted)", marginTop: 4 }}>{d.rain}mm · {d.wind}km/h</div>
              </div>
            ))}
          </div>
          <div style={{ fontSize: 11.5, color: "var(--muted)", marginTop: 12 }}>
            Apto: lluvia &lt; 5 mm · viento 3–15 km/h · temp &lt; 32 °C. Score 0–100.
          </div>
        </>
      )}
    </Card>
  );
}

function ClimateTab() {
  const [q, setQ] = oState("");
  const query = q.trim().toLowerCase();
  const days = WEATHER.filter((w) => !query || w.day.toLowerCase().includes(query));
  return (
    <Page>
      <Topbar title="Clima" subtitle="Pronóstico + ventana de pulverización operativa" range="7 días" onSearch={setQ} searchPlaceholder="Buscar día…" />
      <div style={{ display: "grid", gridTemplateColumns: "repeat(4,1fr)", gap: 16, marginBottom: 18 }}>
        <KPI icon={Icons.thermo} label="Temperatura" value="26" unit="°C" delta={3} />
        <KPI icon={Icons.drop} label="Humedad" value="58" unit="%" delta={-2} deltaGood />
        <KPI icon={Icons.rain} label="Lluvia (7d)" value="19" unit="mm" delta={12} />
        <KPI icon={Icons.sun} label="Grados-día" value="1.142" delta={4} />
      </div>
      <div style={{ marginBottom: 18 }}>
        <SprayWindowPanel />
      </div>
      <div style={{ display: "grid", gridTemplateColumns: "1.5fr 1fr", gap: 18, alignItems: "start" }}>
        <div style={{ display: "flex", flexDirection: "column", gap: 18 }}>
          <Card title="Pronóstico de 7 días" sub="Estancia El Quebracho · Córdoba">
            <div style={{ display: "flex", flexDirection: "column" }}>
              {days.map((w, i) => {
                const C = { sun: Icons.sun, cloud: Icons.cloud, rain: Icons.rain }[w.cond];
                return (
                  <div key={w.day} style={{ display: "grid", gridTemplateColumns: "0.7fr 0.5fr 1.4fr 1fr 0.8fr", gap: 12, alignItems: "center",
                    padding: "12px 4px", borderBottom: i < days.length - 1 ? "1px solid rgba(0,0,0,0.05)" : "none", fontSize: 13.5 }}>
                    <span style={{ fontWeight: 600 }}>{w.day === "Mar" ? "Hoy" : w.day}</span>
                    <span style={{ color: w.cond === "rain" ? "#3f7fb0" : w.cond === "sun" ? "#b58a16" : "var(--muted)" }}><C size={20} /></span>
                    <span><b>{w.t}°</b> <span style={{ color: "var(--muted)" }}>/ {w.lo}°</span></span>
                    <div style={{ display: "flex", alignItems: "center", gap: 8 }}>
                      <Icons.drop size={14} />
                      <div style={{ flex: 1, height: 6, borderRadius: 4, background: "#e2e4d6", overflow: "hidden", maxWidth: 80 }}>
                        <div style={{ height: "100%", width: `${w.rain}%`, background: "#3f7fb0", borderRadius: 4 }} />
                      </div>
                      <span style={{ fontSize: 12, color: "var(--muted)" }}>{w.rain}%</span>
                    </div>
                    <span style={{ textAlign: "right", color: "var(--muted)", fontSize: 12.5 }}>ET {w.et}mm</span>
                  </div>
                );
              })}
            </div>
          </Card>
          <Card title="Temperatura y evapotranspiración" sub="°C y mm/día">
            <LineChart height={170} fill={false}
              series={[{ data: WEATHER.map((w) => w.t) }, { data: WEATHER.map((w) => w.et * 5) }]}
              colors={["#cf7a3a", "#3a6b22"]} dashed={[1]} labels={WEATHER.map((w) => w.day)} min={0} max={30} />
          </Card>
        </div>
        <div style={{ display: "flex", flexDirection: "column", gap: 18 }}>
          <AIInsight insight={AI_INSIGHTS.climate} />
          <Card title="Riesgo de helada" sub="Próximos 7 días">
            <Gauge value={12} max={100} label="Bajo" sub="12% probabilidad" color="#3a6b22" size={170} />
          </Card>
          <Card title="Pronóstico de lluvia" sub="mm por día">
            <BarsV data={WEATHER.map((w) => w.rain / 5)} labels={WEATHER.map((w) => w.day)} height={120} accent="#3f7fb0" highlight={3} />
          </Card>
        </div>
      </div>
    </Page>
  );
}

/* ---------------- PLAGAS ---------------- */
function PestsTab() {
  const [q, setQ] = oState("");
  const query = q.trim().toLowerCase();
  const rows = PESTS.filter((p) => !query || (p.name + " " + p.field + " " + p.crop + " " + p.type).toLowerCase().includes(query));
  return (
    <Page>
      <Topbar title="Plagas y enfermedades" subtitle="Vigilancia de riesgo con IA en todos los campos" range="Esta semana" onSearch={setQ} searchPlaceholder="Buscar amenaza…" />
      <div style={{ display: "grid", gridTemplateColumns: "repeat(4,1fr)", gap: 16, marginBottom: 18 }}>
        <KPI icon={Icons.bug} label="Amenazas activas" value="5" delta={1} deltaGood={false} />
        <KPI icon={Icons.alert} label="Campos de alto riesgo" value="2" delta={1} deltaGood={false} />
        <KPI icon={Icons.gauge} label="Índice de riesgo medio" value="56" unit="/100" delta={8} deltaGood={false} />
        <KPI icon={Icons.shield} label="Tratadas esta semana" value="3" delta={2} />
      </div>
      <div style={{ display: "grid", gridTemplateColumns: "1.5fr 1fr", gap: 18, alignItems: "start" }}>
        <div style={{ display: "flex", flexDirection: "column", gap: 18 }}>
          <Card title="Lista de amenazas" sub="Detectadas por modelos de imagen + clima de riesgo">
            <div style={{ display: "grid", gridTemplateColumns: "1.5fr 1.2fr 1.4fr 0.7fr 1.1fr", gap: 8, fontSize: 11.5, color: "var(--muted)", fontWeight: 600, padding: "0 4px 10px", borderBottom: "1px solid rgba(0,0,0,0.06)" }}>
              <span>AMENAZA</span><span>CAMPO / CULTIVO</span><span>RIESGO</span><span>TEND.</span><span style={{ textAlign: "right" }}>NIVEL</span>
            </div>
            {rows.map((p) => (
              <div key={p.name} onClick={() => window.askAI(`${p.name} en ${p.field} (${p.crop}) tiene riesgo ${p.risk}/100. ¿Qué me recomiendas?`)} className="row-hover"
                style={{ display: "grid", gridTemplateColumns: "1.5fr 1.2fr 1.4fr 0.7fr 1.1fr", gap: 8, alignItems: "center", fontSize: 13.5, padding: "12px 4px", borderBottom: "1px solid rgba(0,0,0,0.04)", cursor: "pointer" }}>
                <div><div style={{ fontWeight: 600 }}>{p.name}</div><div style={{ fontSize: 11.5, color: "var(--muted)" }}>{p.type}</div></div>
                <div style={{ color: "var(--ink-2)" }}>{p.field}<div style={{ fontSize: 11.5, color: "var(--muted)" }}>{p.crop}</div></div>
                <div style={{ display: "flex", alignItems: "center", gap: 8 }}>
                  <div style={{ flex: 1, maxWidth: 80, height: 6, borderRadius: 4, background: "#e2e4d6", overflow: "hidden" }}>
                    <div style={{ height: "100%", width: `${p.risk}%`, borderRadius: 4, background: LEVEL[p.level].color }} />
                  </div>
                  <span style={{ fontWeight: 700, fontSize: 12.5 }}>{p.risk}</span>
                </div>
                <span style={{ color: p.trend === "up" ? "#c0492f" : p.trend === "down" ? "#4f8a2f" : "var(--muted)" }}><Trend t={p.trend} /></span>
                <div style={{ display: "flex", justifyContent: "flex-end" }}><LevelBadge level={p.level} /></div>
              </div>
            ))}
            {rows.length === 0 && <div style={{ padding: "20px 4px", fontSize: 13.5, color: "var(--muted)" }}>Sin amenazas que coincidan.</div>}
          </Card>
          <Card title="Puntos de monitoreo" sub="Lote Este — ruta recomendada en rojo">
            <div style={{ display: "grid", gridTemplateColumns: "repeat(6,1fr)", gap: 6 }}>
              {Array.from({ length: 24 }).map((_, i) => {
                const hot = [9, 10, 15, 16, 22].includes(i);
                const warm = [3, 8, 11, 17, 21].includes(i);
                return <div key={i} style={{ aspectRatio: "1", borderRadius: 8, background: hot ? "#c0492f" : warm ? "#d6a93a" : "#7ba83c", opacity: hot ? 1 : warm ? 0.85 : 0.55 }} />;
              })}
            </div>
          </Card>
        </div>
        <div style={{ display: "flex", flexDirection: "column", gap: 18 }}>
          <AIInsight insight={AI_INSIGHTS.pests} />
          <Card title="Mayor riesgo de enfermedad" sub="Roya asiática · Lote Este">
            <Gauge value={82} max={100} label="82" sub="índice de riesgo" color="#c0492f" size={170} />
            <div style={{ display: "flex", alignItems: "center", gap: 8, marginTop: 8, fontSize: 13, color: "var(--ink-2)" }}>
              <Icons.alert size={16} /> Tratar en 48 h
            </div>
          </Card>
          <Card title="Riesgo por campo" sub="índice /100">
            <BarsH max={100} rows={[
              { label: "Lote Este", value: 78, color: "#c0492f" },
              { label: "Potrero O.", value: 71, color: "#c0492f" },
              { label: "Media Loma", value: 66, color: "#d6a93a" },
              { label: "Lote Norte", value: 62, color: "#d6a93a" },
              { label: "Lote Sur", value: 48, color: "#7ba83c" },
            ]} />
          </Card>
        </div>
      </div>
    </Page>
  );
}

Object.assign(window, { IrrigationTab, ClimateTab, PestsTab });
