/* global React, Icons, CHEMICALS, CHEM_TYPE, APPLICATIONS, PHI_ACTIVE, SPRAY_RECS, FIELDS, AI_INSIGHTS, Card, KPI, AIInsight, Topbar, Page, CampoEngine */
const { useState: cState, useMemo: cMemo, useEffect: cEffect } = React;

const TypeChip = ({ type }) => (
  <span style={{ fontSize: 11.5, fontWeight: 700, color: CHEM_TYPE[type], background: CHEM_TYPE[type] + "22",
    padding: "3px 10px", borderRadius: 999, whiteSpace: "nowrap" }}>{type}</span>
);

const AppStatus = ({ status }) => {
  const applied = status === "applied";
  return (
    <span style={{ display: "inline-flex", alignItems: "center", gap: 6, fontSize: 12.5, fontWeight: 600, whiteSpace: "nowrap",
      color: applied ? "#4f8a2f" : "#b58a16", background: applied ? "rgba(123,180,60,0.15)" : "rgba(214,170,40,0.16)",
      padding: "4px 11px", borderRadius: 999 }}>
      {applied ? <Icons.check size={13} /> : <Icons.clock size={13} />}{applied ? "Aplicado" : "Programado"}
    </span>
  );
};

function ApplicationLog({ query }) {
  const q = (query || "").trim().toLowerCase();
  const rows = q ? APPLICATIONS.filter((a) => (a.product + " " + a.type + " " + a.field).toLowerCase().includes(q)) : APPLICATIONS;
  return (
    <Card title="Registro de aplicaciones" sub="Fumigación y fertilizante · esta temporada"
      action={<button onClick={() => window.toast("Aplicación registrada en el historial")} className="pill" style={{ border: "none", background: "var(--lime)", fontFamily: "Onest", fontWeight: 600, fontSize: 13, padding: "8px 15px", cursor: "pointer", display: "inline-flex", alignItems: "center", gap: 6 }}><Icons.plus size={15} /> Registrar aplicación</button>}>
      <div style={{ display: "grid", gridTemplateColumns: "0.7fr 1.2fr 1fr 0.9fr 0.9fr 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>FECHA</span><span>PRODUCTO</span><span>TIPO</span><span>CAMPO</span><span>DOSIS</span><span style={{ textAlign: "right" }}>ESTADO</span>
      </div>
      {rows.map((a, i) => (
        <div key={i} style={{ display: "grid", gridTemplateColumns: "0.7fr 1.2fr 1fr 0.9fr 0.9fr 1fr", gap: 8, alignItems: "center", fontSize: 13.5, padding: "12px 4px", borderBottom: "1px solid rgba(0,0,0,0.04)" }}>
          <span style={{ color: "var(--muted)", fontSize: 12.5 }}>{a.date}</span>
          <span style={{ fontWeight: 600 }}>{a.product}</span>
          <TypeChip type={a.type} />
          <span style={{ color: "var(--ink-2)" }}>{a.field}</span>
          <span style={{ color: "var(--ink-2)" }}>{a.rate}</span>
          <div style={{ display: "flex", justifyContent: "flex-end" }}><AppStatus status={a.status} /></div>
        </div>
      ))}
      {rows.length === 0 && <div style={{ padding: "20px 4px", fontSize: 13.5, color: "var(--muted)" }}>Sin aplicaciones que coincidan.</div>}
    </Card>
  );
}

function SprayRecs() {
  const eng = window.CampoEngine;
  const presc = eng
    ? eng.buildPrescriptionsFromCatalog({ sprayRecs: SPRAY_RECS, chemicals: CHEMICALS, fields: FIELDS }).filter((p) => p.ok)
    : [];
  const byKey = Object.fromEntries(presc.map((p) => [p.field + "|" + p.product, p]));

  return (
    <Card title="Aplicaciones recomendadas" sub="Riesgo × dosis/ha × total de producto">
      <div style={{ display: "flex", flexDirection: "column", gap: 12 }}>
        {SPRAY_RECS.map((r) => {
          const p = byKey[r.field + "|" + r.product];
          return (
            <div key={r.threat} style={{ display: "flex", alignItems: "center", gap: 14, padding: "12px 14px", borderRadius: 14, background: "#f0f1e8" }}>
              <div style={{ width: 40, height: 40, borderRadius: 12, background: r.level === "high" ? "rgba(200,90,60,0.14)" : "rgba(214,170,40,0.16)",
                color: r.level === "high" ? "#c0492f" : "#b58a16", flex: "none", display: "flex", alignItems: "center", justifyContent: "center" }}><Icons.spray size={20} /></div>
              <div style={{ flex: 1, minWidth: 0 }}>
                <div style={{ fontSize: 14.5, fontWeight: 600 }}>{r.product} <span style={{ color: "var(--muted)", fontWeight: 500, fontSize: 13 }}>· {r.rate}</span></div>
                <div style={{ fontSize: 12.5, color: "var(--muted)" }}>
                  {r.threat} en {r.field} · PC {r.phi} d
                  {p ? ` · Total ${p.totalQty} ${p.unit}${p.costTotal != null ? ` · USD ${p.costTotal}` : ""}` : ""}
                </div>
              </div>
              <button
                onClick={() => window.askAI(`Armame la prescripción completa de ${r.product} para ${r.field} (${r.threat}) con dosis/ha y total.`)}
                className="btn-lime" style={{ padding: "9px 16px", borderRadius: 999, fontSize: 13, flex: "none" }}
              >Calcular</button>
            </div>
          );
        })}
      </div>
    </Card>
  );
}

/** A) Calculadora dosis × ha */
function DoseCalculator() {
  const fields = FIELDS || [];
  const chems = (CHEMICALS || []).filter((c) => c.rateHa != null);
  const [fieldId, setFieldId] = cState(fields[0]?.id || "");
  const [brand, setBrand] = cState(chems[0]?.brand || "");
  const [rate, setRate] = cState(String(chems[0]?.rateHa ?? 0.5));
  const [area, setArea] = cState(String(fields[0]?.area ?? 100));

  const field = fields.find((f) => f.id === fieldId) || fields[0];
  const chem = chems.find((c) => c.brand === brand) || chems[0];

  const onField = (id) => {
    setFieldId(id);
    const f = fields.find((x) => x.id === id);
    if (f) setArea(String(f.area));
  };
  const onChem = (b) => {
    setBrand(b);
    const c = chems.find((x) => x.brand === b);
    if (c?.rateHa != null) setRate(String(c.rateHa));
  };

  const result = cMemo(() => {
    if (!window.CampoEngine || !chem) return null;
    return window.CampoEngine.calcPrescription({
      product: chem.brand,
      field: field?.name,
      target: chem.target,
      rateHa: parseFloat(rate),
      areaHa: parseFloat(area),
      unit: chem.unit === "kg" ? "kg" : "L",
      stock: chem.stock,
      pricePerUnit: chem.pricePerUnit,
      phiDays: chem.phi,
      reiHours: chem.rei,
    });
  }, [fieldId, brand, rate, area]);

  const box = { flex: 1, minWidth: 0 };
  const label = { fontSize: 11.5, fontWeight: 600, color: "var(--muted)", marginBottom: 6, display: "block" };
  const input = {
    width: "100%", border: "1px solid rgba(0,0,0,0.08)", background: "#fff", borderRadius: 12,
    padding: "10px 12px", fontFamily: "Onest", fontSize: 14, color: "var(--ink)", outline: "none",
  };

  return (
    <Card title="Calculadora dosis / ha" sub="Producto × superficie → litros/kg totales, costo y stock"
      action={<button onClick={() => result?.ok && window.askAI(`Validá esta prescripción:\n${result.summary}`)} className="pill" style={{ border: "none", background: "var(--lime)", fontFamily: "Onest", fontWeight: 600, fontSize: 13, padding: "8px 15px", cursor: "pointer" }}>Preguntar al Agrónomo</button>}>
      <div style={{ display: "grid", gridTemplateColumns: "1.2fr 1.2fr 0.7fr 0.7fr", gap: 12, marginBottom: 16 }}>
        <div style={box}>
          <label style={label}>Lote</label>
          <select value={fieldId} onChange={(e) => onField(e.target.value)} style={input}>
            {fields.map((f) => <option key={f.id} value={f.id}>{f.name} · {f.area} ha · {f.crop}</option>)}
          </select>
        </div>
        <div style={box}>
          <label style={label}>Producto</label>
          <select value={brand} onChange={(e) => onChem(e.target.value)} style={input}>
            {chems.map((c) => <option key={c.brand} value={c.brand}>{c.brand} · {c.type}</option>)}
          </select>
        </div>
        <div style={box}>
          <label style={label}>Dosis / ha</label>
          <input type="number" step="0.01" value={rate} onChange={(e) => setRate(e.target.value)} style={input} />
        </div>
        <div style={box}>
          <label style={label}>Hectáreas</label>
          <input type="number" step="1" value={area} onChange={(e) => setArea(e.target.value)} style={input} />
        </div>
      </div>
      {result?.ok && (
        <div style={{ display: "grid", gridTemplateColumns: "repeat(4,1fr)", gap: 12 }}>
          {[
            { label: "Total producto", value: `${result.totalQty} ${result.unit}` },
            { label: "Costo / ha", value: result.costHa != null ? `USD ${result.costHa}` : "—" },
            { label: "Costo total", value: result.costTotal != null ? `USD ${result.costTotal}` : "—" },
            { label: "Stock", value: result.stockOk == null ? "—" : result.stockOk ? "Suficiente" : `Faltan ${result.stockGap} ${result.unit}` },
          ].map((k) => (
            <div key={k.label} style={{ background: "#f0f1e8", borderRadius: 14, padding: "14px 16px" }}>
              <div style={{ fontSize: 11.5, color: "var(--muted)", fontWeight: 600 }}>{k.label}</div>
              <div style={{ fontSize: 18, fontWeight: 800, marginTop: 4, color: k.label === "Stock" && result.stockOk === false ? "#c0492f" : "var(--ink)" }}>{k.value}</div>
            </div>
          ))}
          <div style={{ gridColumn: "1 / -1", fontSize: 12.5, color: "var(--muted)" }}>
            PHI {result.phiDays ?? "—"} d · Reingreso {result.reiHours ?? "—"} h · ⚠️ Verificar marbete SENASA
          </div>
        </div>
      )}
      {result && !result.ok && <div style={{ color: "#c0492f", fontSize: 13.5 }}>{result.error}</div>}
    </Card>
  );
}

function ProductStore() {
  return (
    <Card title="Almacén de productos" sub="Stock de químicos y fertilizantes">
      <div style={{ display: "flex", flexDirection: "column", gap: 15 }}>
        {CHEMICALS.map((c) => (
          <div key={c.brand}>
            <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center", marginBottom: 7 }}>
              <div style={{ display: "flex", alignItems: "center", gap: 9, minWidth: 0 }}>
                <span style={{ width: 9, height: 9, borderRadius: 3, background: CHEM_TYPE[c.type], flex: "none" }} />
                <span style={{ fontSize: 14, fontWeight: 600, whiteSpace: "nowrap" }}>{c.brand}</span>
                <span style={{ fontSize: 12, color: "var(--muted)", whiteSpace: "nowrap", overflow: "hidden", textOverflow: "ellipsis" }}>{c.name}</span>
              </div>
              <span style={{ fontSize: 13, fontWeight: 700, color: c.stock < 15 ? "#c0492f" : "var(--ink)", flex: "none", whiteSpace: "nowrap" }}>{c.stock}{c.unit === "L" ? " L" : "%"}</span>
            </div>
            <div style={{ height: 7, borderRadius: 5, background: "#e2e4d6", overflow: "hidden" }}>
              <div style={{ height: "100%", borderRadius: 5, background: c.stock < 15 ? "#c0492f" : CHEM_TYPE[c.type],
                width: `${c.unit === "L" ? Math.min(c.stock, 100) : c.stock}%` }} />
            </div>
          </div>
        ))}
      </div>
    </Card>
  );
}

function Compliance() {
  return (
    <Card title="Cumplimiento · PC" sub="Días hasta cosecha segura" action={<Icons.shield size={18} />}>
      <div style={{ display: "flex", flexDirection: "column", gap: 14 }}>
        {PHI_ACTIVE.map((p) => {
          const remaining = p.phi - p.elapsed;
          return (
            <div key={p.field}>
              <div style={{ display: "flex", justifyContent: "space-between", alignItems: "baseline", marginBottom: 7 }}>
                <span style={{ fontSize: 14, fontWeight: 600 }}>{p.field} <span style={{ color: "var(--muted)", fontWeight: 500, fontSize: 12.5 }}>· {p.product}</span></span>
                <span style={{ fontSize: 13, fontWeight: 700, color: "#b58a16" }}>{remaining} d rest.</span>
              </div>
              <div style={{ height: 7, borderRadius: 5, background: "#e2e4d6", overflow: "hidden" }}>
                <div style={{ height: "100%", borderRadius: 5, background: "#b58a16", width: `${(p.elapsed / p.phi) * 100}%` }} />
              </div>
            </div>
          );
        })}
        <div style={{ display: "flex", alignItems: "center", gap: 10, marginTop: 2, fontSize: 12.5, color: "var(--muted)" }}>
          <Icons.checkCircle size={16} /> 6 campos más listos para cosechar
        </div>
      </div>
    </Card>
  );
}

function ApplicationSlotCard() {
  const [job, setJob] = cState("contact");
  const [data, setData] = cState(null);
  const [err, setErr] = cState("");
  const coords = window.FARM_COORDS || { lat: -31.4173, lng: -63.2438 };

  cEffect(() => {
    const qs = new URLSearchParams({
      lat: coords.lat,
      lng: coords.lng,
      job,
    });
    setErr("");
    fetch(`/api/weather?${qs}`)
      .then((r) => r.json())
      .then((d) => {
        window.__APPLY_SLOT = d.applicationSlot || null;
        setData(d);
      })
      .catch((e) => setErr(String(e.message || e)));
  }, [job, coords.lat, coords.lng]);

  const slot = data && data.applicationSlot;
  const tone = slot && slot.verdict === "apply" ? "#4f8a2f" : slot && slot.verdict === "no" ? "#c0492f" : "#b58a16";
  const bg = slot && slot.verdict === "apply" ? "rgba(123,180,60,0.14)" : slot && slot.verdict === "no" ? "rgba(200,90,60,0.14)" : "rgba(214,170,40,0.16)";

  return (
    <Card title="Semáforo de aplicación" sub="ΔT (INTA/Aapresid) · humedad 0–7 cm · lluvia · suelo INTA — no reemplaza el marbete"
      action={
        <div className="seg">
          <button className={job === "contact" ? "active" : ""} onClick={() => setJob("contact")}>Foliar / contacto</button>
          <button className={job === "residual" ? "active" : ""} onClick={() => setJob("residual")}>Residual</button>
        </div>
      }>
      {!slot && !err && <div style={{ fontSize: 13.5, color: "var(--muted)" }}>Consultando clima + INTA…</div>}
      {err && <div style={{ fontSize: 13.5, color: "#c0492f" }}>{err}</div>}
      {slot && (
        <div>
          <div style={{ display: "flex", alignItems: "center", gap: 14, marginBottom: 14 }}>
            <div style={{ background: bg, color: tone, borderRadius: 16, padding: "10px 16px", fontWeight: 800, fontSize: 18, minWidth: 120, textAlign: "center" }}>
              {slot.label}
            </div>
            <div style={{ fontSize: 13.5, color: "var(--ink-2)", lineHeight: 1.4 }}>
              Score {slot.score} · ΔT {slot.deltaT ?? "—"} °C · viento {slot.wind ?? "—"} km/h
              {data.inta && data.inta.orden_sue1 ? ` · ${data.inta.orden_sue1}` : ""}
              <div style={{ color: "var(--muted)", fontSize: 12.5, marginTop: 4 }}>{slot.summary.replace(/\*\*/g, "")}</div>
            </div>
          </div>
          <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 8 }}>
            {(slot.checks || []).map((c) => (
              <div key={c.id} style={{ background: "#f0f1e8", borderRadius: 12, padding: "10px 12px", borderLeft: `3px solid ${c.ok ? "#4f8a2f" : "#c0492f"}` }}>
                <div style={{ fontSize: 13, fontWeight: 700 }}>{c.ok ? "OK" : "Atención"} · {c.label}</div>
                <div style={{ fontSize: 12, color: "var(--muted)", marginTop: 3, lineHeight: 1.4 }}>{c.detail}</div>
              </div>
            ))}
          </div>
          <div style={{ marginTop: 12, display: "flex", justifyContent: "space-between", alignItems: "center", gap: 12 }}>
            <span style={{ fontSize: 12, color: "var(--muted)" }}>{slot.disclaimer}</span>
            <button className="btn-lime" style={{ padding: "8px 14px", borderRadius: 999, fontSize: 13, flex: "none" }}
              onClick={() => window.askAI(job === "residual"
                ? "¿Puedo tirar un preemergente hoy? Usá el semáforo (ΔT, humedad de suelo, lluvia 7 días e INTA)."
                : "¿Puedo pulverizar foliar hoy? Usá el semáforo de ΔT, viento, lluvia 6 h e INTA.")}>
              Preguntar al Agrónomo
            </button>
          </div>
        </div>
      )}
    </Card>
  );
}

function ChemicalsTab() {
  const [query, setQuery] = cState("");
  return (
    <Page>
      <Topbar title="Químicos y aplicaciones" subtitle="Semáforo ΔT + suelo, dosis/ha, almacén y SENASA" range="Campaña 2025/26" onSearch={setQuery} searchPlaceholder="Buscar producto…" />
      <div style={{ marginBottom: 18 }}>
        <ApplicationSlotCard />
      </div>
      <div style={{ display: "grid", gridTemplateColumns: "repeat(4,1fr)", gap: 16, marginBottom: 18 }}>
        <KPI icon={Icons.flask} label="Productos en almacén" value="6" delta={0} />
        <KPI icon={Icons.spray} label="Aplicaciones (temporada)" value="24" delta={9} deltaGood={false} />
        <KPI icon={Icons.shield} label="Lotes en carencia" value="2" delta={1} deltaGood={false} />
        <KPI icon={Icons.dollar} label="Gasto en químicos" value="USD 38k" delta={-6} deltaGood />
      </div>
      <div style={{ marginBottom: 18 }}>
        <DoseCalculator />
      </div>
      <div style={{ display: "grid", gridTemplateColumns: "1.5fr 1fr", gap: 18, alignItems: "start" }}>
        <div style={{ display: "flex", flexDirection: "column", gap: 18 }}>
          <ApplicationLog query={query} />
          <SprayRecs />
        </div>
        <div style={{ display: "flex", flexDirection: "column", gap: 18 }}>
          <AIInsight insight={AI_INSIGHTS.chemicals} />
          <ProductStore />
          <Compliance />
        </div>
      </div>
    </Page>
  );
}
window.ChemicalsTab = ChemicalsTab;
