/* global React, Icons, FARM, FIELDS, WEATHER, PESTS, AI_INSIGHTS, NDVI_HISTORY, YIELD_FORECAST, Card, KPI, AIInsight, StatusBadge, Topbar, LineChart, Spark, BarsV, CampoEngine */
const { useState: dState, useMemo: dMemo } = React;

const condIcon = { sun: Icons.sun, cloud: Icons.cloud, rain: Icons.rain };

function MiniWeather() {
  const today = WEATHER[1];
  return (
    <Card title="Clima" sub={FARM.name} action={<span style={{ fontSize: 12.5, color: "var(--muted)" }}>Córdoba</span>}>
      <div style={{ display: "flex", alignItems: "center", gap: 16, marginBottom: 18 }}>
        <div style={{ width: 56, height: 56, borderRadius: 16, background: "rgba(214,200,40,0.16)", color: "#b58a16",
          display: "flex", alignItems: "center", justifyContent: "center" }}><Icons.sun size={30} /></div>
        <div>
          <div style={{ fontSize: 34, fontWeight: 800, letterSpacing: "-0.02em", lineHeight: 1 }}>{today.t}°<span style={{ fontSize: 16, color: "var(--muted)", fontWeight: 600 }}> / {today.lo}°</span></div>
          <div style={{ fontSize: 13.5, color: "var(--muted)", marginTop: 3 }}>Soleado · {today.rain}% lluvia · {today.wind} km/h</div>
        </div>
      </div>
      <div style={{ display: "flex", justifyContent: "space-between", borderTop: "1px solid rgba(0,0,0,0.06)", paddingTop: 14 }}>
        {WEATHER.map((w) => {
          const C = condIcon[w.cond];
          return (
            <div key={w.day} style={{ display: "flex", flexDirection: "column", alignItems: "center", gap: 6 }}>
              <span style={{ fontSize: 11.5, color: "var(--muted)" }}>{w.day}</span>
              <C size={17} />
              <span style={{ fontSize: 12.5, fontWeight: 700 }}>{w.t}°</span>
            </div>
          );
        })}
      </div>
    </Card>
  );
}

const alertItems = [
  { icon: Icons.drop, color: "#c0492f", bg: "rgba(200,90,60,0.13)", title: "Estrés hídrico — Lote Este", sub: "Humedad del suelo 33%, bajo el umbral", q: "El Lote Este (soja) tiene estrés hídrico (humedad 33%, NDVI 0,45). ¿Qué hago?" },
  { icon: Icons.bug, color: "#b58a16", bg: "rgba(214,170,40,0.16)", title: "Roya de la hoja — Potrero Oeste", sub: "Riesgo de enfermedad al 71%", q: "El Potrero Oeste (trigo) tiene 71% de riesgo de roya de la hoja. ¿Cómo lo trato?" },
  { icon: Icons.leaf, color: "#c0492f", bg: "rgba(200,90,60,0.13)", title: "NDVI bajo — Media Loma", sub: "El vigor del sorgo cayó a 0,38", q: "El NDVI de Media Loma (sorgo) cayó a 0,38. ¿Qué puede estar pasando?" },
];

function Alerts({ go }) {
  return (
    <Card title="Alertas prioritarias" action={<span onClick={() => go("notifications")} style={{ fontSize: 12.5, color: "var(--muted)", cursor: "pointer", fontWeight: 600 }}>Ver todas</span>}>
      <div style={{ display: "flex", flexDirection: "column", gap: 12 }}>
        {alertItems.map((a) => (
          <div key={a.title} onClick={() => window.askAI(a.q)} className="row-hover" style={{ display: "flex", alignItems: "center", gap: 13, padding: "6px 8px", margin: "0 -8px", borderRadius: 12, cursor: "pointer" }}>
            <div style={{ width: 38, height: 38, borderRadius: 11, background: a.bg, color: a.color, flex: "none",
              display: "flex", alignItems: "center", justifyContent: "center" }}><a.icon size={19} /></div>
            <div style={{ lineHeight: 1.3, minWidth: 0 }}>
              <div style={{ fontSize: 14, fontWeight: 600 }}>{a.title}</div>
              <div style={{ fontSize: 12.5, color: "var(--muted)" }}>{a.sub}</div>
            </div>
          </div>
        ))}
      </div>
    </Card>
  );
}

function FieldsTable({ go, query }) {
  const q = (query || "").trim().toLowerCase();
  const rows = q ? FIELDS.filter((f) => (f.name + " " + f.crop + " " + f.zone).toLowerCase().includes(q)) : FIELDS;
  return (
    <Card title="Resumen de campos" sub={`${FARM.fieldsCount} campos · ${FARM.cultivated} ha cultivadas`}
      action={<button onClick={() => go("fields")} className="pill" style={{ border: "none", background: "#eceede", fontFamily: "Onest", fontWeight: 600, fontSize: 13, padding: "8px 14px", cursor: "pointer", display: "inline-flex", alignItems: "center", gap: 6 }}>Abrir mapa <Icons.arrowRight size={14} /></button>}>
      <div style={{ display: "grid", gridTemplateColumns: "1.5fr 1fr 0.8fr 1.3fr 0.9fr 1fr", gap: 8, fontSize: 11.5,
        color: "var(--muted)", fontWeight: 600, padding: "0 6px 10px", borderBottom: "1px solid rgba(0,0,0,0.06)" }}>
        <span>CAMPO</span><span>CULTIVO</span><span>ÁREA</span><span>NDVI</span><span>RENDIM.</span><span style={{ textAlign: "right" }}>ESTADO</span>
      </div>
      <div>
        {rows.map((f) => (
          <div key={f.id} onClick={() => window.openField(f.id)} className="row-hover" style={{ display: "grid",
            gridTemplateColumns: "1.5fr 1fr 0.8fr 1.3fr 0.9fr 1fr", gap: 8, alignItems: "center", fontSize: 13.5,
            padding: "11px 6px", borderBottom: "1px solid rgba(0,0,0,0.04)", cursor: "pointer" }}>
            <span style={{ fontWeight: 600 }}>{f.name}</span>
            <span style={{ color: "var(--ink-2)" }}>{f.crop}</span>
            <span style={{ color: "var(--ink-2)" }}>{f.area} ha</span>
            <div style={{ display: "flex", alignItems: "center", gap: 8 }}>
              <div style={{ flex: 1, maxWidth: 70, height: 6, borderRadius: 4, background: "#e2e4d6", overflow: "hidden" }}>
                <div style={{ height: "100%", width: `${f.ndvi * 100}%`, borderRadius: 4,
                  background: f.ndvi > 0.55 ? "#4f8a2f" : f.ndvi > 0.42 ? "#c6cf4a" : "#cf9b4a" }} />
              </div>
              <span style={{ fontWeight: 600, fontSize: 12.5 }}>{f.ndvi.toFixed(2)}</span>
            </div>
            <span style={{ fontWeight: 600 }}>{f.yieldPred} <span style={{ color: "var(--muted)", fontSize: 11, fontWeight: 500 }}>{f.unit}</span></span>
            <div style={{ display: "flex", justifyContent: "flex-end" }}><StatusBadge status={f.status} /></div>
          </div>
        ))}
        {rows.length === 0 && <div style={{ padding: "22px 6px", fontSize: 13.5, color: "var(--muted)" }}>Sin resultados para “{query}”.</div>}
      </div>
    </Card>
  );
}

/** B) NDVI satelital por lote */
function NdviSatelliteCard() {
  const rows = dMemo(() => {
    if (!window.CampoEngine) return [];
    return window.CampoEngine.analyzeAllFieldsNdvi(FIELDS).sort((a, b) => a.current - b.current);
  }, []);
  const alerts = rows.filter((r) => r.alert);

  return (
    <Card
      title="NDVI satelital"
      sub={`Sentinel-2 (demo) · ${alerts.length} alerta(s) de caída`}
      action={
        <button
          onClick={() => window.askAI("¿Qué dice el NDVI satelital? Priorizá lotes con caída de vigor.")}
          className="pill"
          style={{ border: "none", background: "var(--lime)", fontFamily: "Onest", fontWeight: 600, fontSize: 12.5, padding: "7px 12px", cursor: "pointer" }}
        >
          Analizar
        </button>
      }
    >
      <div style={{ display: "flex", flexDirection: "column", gap: 10 }}>
        {rows.slice(0, 5).map((n) => (
          <div key={n.fieldId} style={{ display: "flex", alignItems: "center", gap: 10 }}>
            <div style={{ flex: 1, minWidth: 0 }}>
              <div style={{ fontSize: 13.5, fontWeight: 600 }}>{n.fieldName} <span style={{ color: "var(--muted)", fontWeight: 500 }}>· {n.crop}</span></div>
              <div style={{ fontSize: 11.5, color: n.alert ? "#c0492f" : "var(--muted)" }}>
                {n.label} · Δ {n.delta7ish > 0 ? "+" : ""}{n.delta7ish}
                {n.alert ? " · " + n.alert.code : ""}
              </div>
            </div>
            <div style={{ width: 72 }}>
              <div style={{ height: 6, borderRadius: 4, background: "#e2e4d6", overflow: "hidden" }}>
                <div style={{
                  height: "100%", width: `${Math.min(100, n.current * 100)}%`, borderRadius: 4,
                  background: n.current >= 0.55 ? "#4f8a2f" : n.current >= 0.42 ? "#c6cf4a" : "#c0492f",
                }} />
              </div>
              <div style={{ fontSize: 12.5, fontWeight: 800, textAlign: "right", marginTop: 3 }}>{n.current.toFixed(2)}</div>
            </div>
          </div>
        ))}
      </div>
    </Card>
  );
}

/** Value proposition metrics for sales / farmer ROI */
function ValuePropCard() {
  const vp = dMemo(() => {
    if (!window.CampoEngine) return null;
    return window.CampoEngine.valueProposition({ cultivated_ha: FARM.cultivated, fieldsCount: FARM.fieldsCount });
  }, []);
  if (!vp) return null;
  const total = vp.metrics.find((m) => m.id === "total");
  const rest = vp.metrics.filter((m) => m.id !== "total");

  return (
    <Card
      title="Valor para el productor"
      sub={`${vp.ha} ha · modelo orientativo de ROI`}
      action={
        <button
          onClick={() => window.askAI("¿Cuánto valor genera PampaGo en mi campo? Justificá con métricas.")}
          className="pill"
          style={{ border: "none", background: "var(--olive-dark)", color: "#f2f3ea", fontFamily: "Onest", fontWeight: 600, fontSize: 12.5, padding: "7px 12px", cursor: "pointer" }}
        >
          Pitch IA
        </button>
      }
    >
      <div style={{
        background: "linear-gradient(135deg, #373c2a, #2d3122)", color: "#f2f3ea",
        borderRadius: 16, padding: "16px 18px", marginBottom: 12,
      }}>
        <div style={{ fontSize: 12, opacity: 0.75, fontWeight: 600 }}>Valor combinado estimado / año</div>
        <div style={{ fontSize: 28, fontWeight: 800, letterSpacing: "-0.02em", marginTop: 4 }}>{total?.value}</div>
        <div style={{ fontSize: 12, opacity: 0.7, marginTop: 4 }}>{total?.detail}</div>
      </div>
      <div style={{ display: "flex", flexDirection: "column", gap: 10 }}>
        {rest.map((m) => (
          <div key={m.id} style={{ display: "flex", justifyContent: "space-between", gap: 12, alignItems: "flex-start" }}>
            <div style={{ minWidth: 0 }}>
              <div style={{ fontSize: 13, fontWeight: 600 }}>{m.label}</div>
              <div style={{ fontSize: 11.5, color: "var(--muted)" }}>{m.detail}</div>
            </div>
            <div style={{ fontSize: 13.5, fontWeight: 800, whiteSpace: "nowrap", color: "#3a6b22" }}>{m.value}</div>
          </div>
        ))}
      </div>
      <div style={{ fontSize: 11, color: "var(--muted)", marginTop: 12, lineHeight: 1.4 }}>
        {vp.paybackNote} {vp.disclaimer}
      </div>
    </Card>
  );
}

function YieldForecast() {
  return (
    <Card title="Pronóstico de rendimiento" sub="Modelo IA · t/ha por temporada"
      action={<div style={{ display: "flex", gap: 14, fontSize: 12, color: "var(--muted)" }}>
        {[["Optimista", "#a7ab98"], ["Esperado", "#3a6b22"], ["Bajo", "#cf9b4a"]].map(([l, c]) => (
          <span key={l} style={{ display: "flex", alignItems: "center", gap: 6 }}><span style={{ width: 9, height: 9, borderRadius: 999, background: c }} />{l}</span>
        ))}
      </div>}>
      <div style={{ display: "flex", alignItems: "baseline", gap: 10, marginBottom: 6 }}>
        <span style={{ fontSize: 32, fontWeight: 800, letterSpacing: "-0.02em", whiteSpace: "nowrap" }}>{FARM.predictedYield.toLocaleString("es-ES")} t</span>
        <span style={{ fontSize: 13.5, color: "#4f8a2f", fontWeight: 700, display: "inline-flex", alignItems: "center", gap: 4 }}><Icons.trendUp size={15} /> +6% vs. temporada pasada</span>
        <span style={{ fontSize: 12.5, color: "var(--muted)", marginLeft: "auto" }}>{FARM.yieldConfidence}% de confianza</span>
      </div>
      <LineChart height={186}
        series={[
          { data: YIELD_FORECAST[1].data },
          { data: YIELD_FORECAST[0].data },
          { data: YIELD_FORECAST[2].data },
        ]}
        colors={["#3a6b22", "#a7ab98", "#cf9b4a"]} dashed={[1, 2]}
        labels={["", "S2", "", "S4", "", "S6", "", "S8", "", "S10", "", "Hoy"]} />
    </Card>
  );
}

function DashboardTab({ go }) {
  const [query, setQuery] = dState("");
  return (
    <window.Page>
      <Topbar title="Buenos días" subtitle={`${FARM.name} · ${FARM.season}`} range="Esta semana" onSearch={setQuery} />
      <div style={{ display: "grid", gridTemplateColumns: "repeat(4, 1fr)", gap: 16, marginBottom: 18 }}>
        <KPI icon={Icons.layers} label="Área cultivada" value={FARM.cultivated} unit="ha" delta={2} spark={[820,840,860,900,920,940,960]} />
        <KPI icon={Icons.ndvi} label="NDVI promedio" value={FARM.avgNDVI.toFixed(2)} delta={3} spark={NDVI_HISTORY.slice(4)} />
        <KPI icon={Icons.sprout} label="Rendimiento previsto" value={FARM.predictedYield.toLocaleString("es-ES")} unit="t" delta={6} spark={[3,4.6,6.9,9.1,10.8,11.6,11.8]} />
        <KPI icon={Icons.drop} label="Agua usada" value={FARM.waterUsedPct} unit="%" delta={-4} deltaGood={true} spark={[40,46,52,55,60,62,64]} sparkColor="#3f7fb0" />
      </div>
      <div style={{ display: "grid", gridTemplateColumns: "1.55fr 1fr", gap: 18, alignItems: "start" }}>
        <div style={{ display: "flex", flexDirection: "column", gap: 18 }}>
          <YieldForecast />
          <FieldsTable go={go} query={query} />
        </div>
        <div style={{ display: "flex", flexDirection: "column", gap: 18 }}>
          <AIInsight insight={AI_INSIGHTS.dashboard} />
          <ValuePropCard />
          <NdviSatelliteCard />
          <MiniWeather />
          <Alerts go={go} />
        </div>
      </div>
    </window.Page>
  );
}
window.DashboardTab = DashboardTab;
