/* global React, Icons, FARM, FIELDS, HARVEST, INPUTS, PRODUCTIVITY, YIELD_FORECAST, AI_INSIGHTS, Card, KPI, AIInsight, StatusBadge, Topbar, LineChart, BarsH, Donut, Page */
const { useState: mState, useEffect: mEffect } = React;

/* ---------------- INVENTARIO ---------------- */
const fmt = (n) => "$" + n.toLocaleString("es-ES");

function InventoryTab() {
  const [q, setQ] = mState("");
  const query = q.trim().toLowerCase();
  const totalValue = HARVEST.reduce((s, h) => s + h.value, 0);
  const donutSegs = HARVEST.map((h, i) => ({ value: h.value, color: ["#3a6b22", "#7ba83c", "#c6cf4a", "#cf9b4a"][i] }));
  const harvest = HARVEST.filter((h) => !query || h.crop.toLowerCase().includes(query));
  return (
    <Page>
      <Topbar title="Inventario" subtitle="Cosecha almacenada e insumos de la finca" range="Actual" onSearch={setQ} searchPlaceholder="Buscar cultivo…" />
      <div style={{ display: "grid", gridTemplateColumns: "repeat(4,1fr)", gap: 16, marginBottom: 18 }}>
        <KPI icon={Icons.dollar} label="Valor de cosecha" value={"$553k"} delta={9} />
        <KPI icon={Icons.box} label="Almacén usado" value="71" unit="%" delta={6} deltaGood={false} />
        <KPI icon={Icons.alert} label="Insumos bajos" value="1" delta={0} />
        <KPI icon={Icons.truck} label="Despachado (mes)" value="312" unit="t" delta={14} />
      </div>
      <div style={{ display: "grid", gridTemplateColumns: "1.5fr 1fr", gap: 18, alignItems: "start" }}>
        <div style={{ display: "flex", flexDirection: "column", gap: 18 }}>
          <Card title="Cosecha almacenada" sub="Toneladas vs. capacidad de silo">
            <div style={{ display: "flex", flexDirection: "column", gap: 18 }}>
              {harvest.map((h) => (
                <div key={h.crop} onClick={() => window.openHarvest(h.crop)} className="row-hover" style={{ cursor: "pointer", padding: "8px 10px", margin: "0 -10px", borderRadius: 12 }}>
                  <div style={{ display: "flex", justifyContent: "space-between", alignItems: "baseline", marginBottom: 7 }}>
                    <span style={{ fontSize: 14.5, fontWeight: 600, display: "flex", alignItems: "center", gap: 7 }}>{h.crop} <Icons.arrowRight size={13} style={{ opacity: 0.4 }} /></span>
                    <span style={{ fontSize: 13, color: "var(--muted)" }}><b style={{ color: "var(--ink)" }}>{h.amount.toLocaleString("es-ES")}{h.unit}</b> / {h.cap.toLocaleString("es-ES")}{h.unit} · {fmt(h.value)}</span>
                  </div>
                  <div style={{ height: 9, borderRadius: 6, background: "#e2e4d6", overflow: "hidden" }}>
                    <div style={{ height: "100%", width: `${(h.amount / h.cap) * 100}%`, borderRadius: 6, background: "#3a6b22" }} />
                  </div>
                </div>
              ))}
              {harvest.length === 0 && <div style={{ fontSize: 13.5, color: "var(--muted)" }}>Sin cultivos que coincidan.</div>}
            </div>
          </Card>
          <Card title="Niveles de insumos" sub="Stock restante · marca de reorden">
            <div style={{ display: "flex", flexDirection: "column", gap: 18 }}>
              {INPUTS.map((inp) => (
                <div key={inp.name}>
                  <div style={{ display: "flex", justifyContent: "space-between", alignItems: "baseline", marginBottom: 7 }}>
                    <span style={{ fontSize: 14.5, fontWeight: 600 }}>{inp.name}</span>
                    <span style={{ fontSize: 13, fontWeight: 700, color: inp.level === "low" ? "#c0492f" : "var(--ink)" }}>{inp.stock}% <span style={{ color: "var(--muted)", fontWeight: 500, fontSize: 11.5 }}>{inp.unit.replace("% ", "")}</span></span>
                  </div>
                  <div style={{ height: 9, borderRadius: 6, background: "#e2e4d6", overflow: "hidden", position: "relative" }}>
                    <div style={{ height: "100%", width: `${inp.stock}%`, borderRadius: 6, background: inp.level === "low" ? "#c0492f" : "#6f9a3a" }} />
                    <div style={{ position: "absolute", top: -2, bottom: -2, left: `${inp.reorder}%`, width: 2, background: "#1b1e14", opacity: 0.35 }} />
                  </div>
                </div>
              ))}
            </div>
          </Card>
        </div>
        <div style={{ display: "flex", flexDirection: "column", gap: 18 }}>
          <Card title="Valor del stock" sub={`Total ${fmt(totalValue)}`}>
            <div style={{ display: "flex", justifyContent: "center", padding: "6px 0 12px" }}>
              <Donut segments={donutSegs} center="$553k" sub="en almacén" size={160} thickness={18} />
            </div>
            <div style={{ display: "flex", flexDirection: "column", gap: 9 }}>
              {HARVEST.map((h, i) => (
                <div key={h.crop} style={{ display: "flex", alignItems: "center", gap: 9, fontSize: 13 }}>
                  <span style={{ width: 9, height: 9, borderRadius: 999, background: ["#3a6b22", "#7ba83c", "#c6cf4a", "#cf9b4a"][i] }} />
                  <span style={{ flex: 1, color: "var(--ink-2)" }}>{h.crop}</span>
                  <span style={{ fontWeight: 700 }}>{fmt(h.value)}</span>
                </div>
              ))}
            </div>
          </Card>
          <Card title="Reordenar pronto" action={<Icons.truck size={18} />}>
            <div onClick={() => window.toast("Pedido de diésel iniciado")} className="row-hover" style={{ display: "flex", alignItems: "center", gap: 12, padding: "6px 8px", margin: "0 -8px", borderRadius: 12, cursor: "pointer" }}>
              <div style={{ width: 38, height: 38, borderRadius: 11, background: "rgba(200,90,60,0.13)", color: "#c0492f", display: "flex", alignItems: "center", justifyContent: "center", flex: "none" }}><Icons.alert size={19} /></div>
              <div><div style={{ fontSize: 14, fontWeight: 600 }}>Diésel — 21%</div><div style={{ fontSize: 12.5, color: "var(--muted)" }}>Bajo el punto de reorden (25%)</div></div>
            </div>
          </Card>
        </div>
      </div>
    </Page>
  );
}

/* ---------------- INFORMES ---------------- */
const lastSeason = YIELD_FORECAST[1].data.map((v) => v * 0.94);
function perf(f) { return Math.round(f.ndvi * 90 + f.change + 10); }

function ReportsTab() {
  const [q, setQ] = mState("");
  const query = q.trim().toLowerCase();
  const sorted = [...FIELDS].sort((a, b) => perf(b) - perf(a)).filter((f) => !query || (f.name + " " + f.crop).toLowerCase().includes(query));
  return (
    <Page>
      <Topbar title="Informes" subtitle="Análisis de rendimiento y desempeño de parcelas" range="Temporada 2026" onSearch={setQ} searchPlaceholder="Buscar campo…" />
      <div style={{ display: "grid", gridTemplateColumns: "repeat(4,1fr)", gap: 16, marginBottom: 18 }}>
        <KPI icon={Icons.sprout} label="Rendimiento previsto" value="1.284" unit="t" delta={6} />
        <KPI icon={Icons.target} label="Área alta productividad" value="42" unit="%" delta={5} />
        <KPI icon={Icons.gauge} label="Rendim. vs. objetivo" value="103" unit="%" delta={3} />
        <KPI icon={Icons.dollar} label="Ganancia / ha" value="$612" delta={8} />
      </div>
      <div style={{ display: "grid", gridTemplateColumns: "1.5fr 1fr", gap: 18, alignItems: "start" }}>
        <div style={{ display: "flex", flexDirection: "column", gap: 18 }}>
          <Card title="Tendencia de rendimiento" sub="t/ha · esta temporada vs. anterior"
            action={<div style={{ display: "flex", gap: 14, fontSize: 12, color: "var(--muted)" }}>
              <span style={{ display: "flex", alignItems: "center", gap: 6 }}><span style={{ width: 9, height: 9, borderRadius: 999, background: "#3a6b22" }} />Esta temporada</span>
              <span style={{ display: "flex", alignItems: "center", gap: 6 }}><span style={{ width: 9, height: 9, borderRadius: 999, background: "#a7ab98" }} />Temporada anterior</span>
            </div>}>
            <LineChart height={180} series={[{ data: YIELD_FORECAST[1].data }, { data: lastSeason }]}
              colors={["#3a6b22", "#a7ab98"]} dashed={[1]} labels={["", "S2", "", "S4", "", "S6", "", "S8", "", "S10", "", "Hoy"]} />
          </Card>
          <Card title="Desempeño por campo" sub="El índice combina NDVI, rendimiento y tendencia">
            <div style={{ display: "grid", gridTemplateColumns: "1.3fr 1fr 0.9fr 1.4fr 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>CAMPO</span><span>CULTIVO</span><span>RENDIM.</span><span>DESEMPEÑO</span><span style={{ textAlign: "right" }}>ESTADO</span>
            </div>
            {sorted.map((f) => {
              const p = perf(f);
              return (
                <div key={f.id} onClick={() => window.openField(f.id)} className="row-hover" style={{ display: "grid", gridTemplateColumns: "1.3fr 1fr 0.9fr 1.4fr 1fr", 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 }}>{f.name}</span>
                  <span style={{ color: "var(--ink-2)" }}>{f.crop}</span>
                  <span style={{ fontWeight: 600 }}>{f.yieldPred}<span style={{ fontSize: 11, color: "var(--muted)" }}> {f.unit}</span></span>
                  <div style={{ display: "flex", alignItems: "center", gap: 8 }}>
                    <div style={{ flex: 1, maxWidth: 90, height: 6, borderRadius: 4, background: "#e2e4d6", overflow: "hidden" }}>
                      <div style={{ height: "100%", width: `${p}%`, borderRadius: 4, background: p > 65 ? "#4f8a2f" : p > 50 ? "#c6cf4a" : "#cf9b4a" }} />
                    </div>
                    <span style={{ fontWeight: 700, fontSize: 12.5 }}>{p}</span>
                  </div>
                  <div style={{ display: "flex", justifyContent: "flex-end" }}><StatusBadge status={f.status} /></div>
                </div>
              );
            })}
            {sorted.length === 0 && <div style={{ padding: "20px 4px", fontSize: 13.5, color: "var(--muted)" }}>Sin campos que coincidan.</div>}
          </Card>
        </div>
        <div style={{ display: "flex", flexDirection: "column", gap: 18 }}>
          <AIInsight insight={AI_INSIGHTS.reports} />
          <Card title="Zonas de productividad" sub="Porción del área de la finca">
            <div style={{ display: "flex", justifyContent: "center", padding: "6px 0 14px" }}>
              <Donut segments={PRODUCTIVITY.map((z) => ({ value: z.pct, color: z.color }))} center="42%" sub="nivel alto" size={160} thickness={18} />
            </div>
            <div style={{ display: "flex", flexDirection: "column", gap: 10 }}>
              {PRODUCTIVITY.map((z) => (
                <div key={z.tier} style={{ display: "flex", alignItems: "center", gap: 9, fontSize: 13 }}>
                  <span style={{ width: 9, height: 9, borderRadius: 999, background: z.color }} />
                  <span style={{ flex: 1, color: "var(--ink-2)" }}>Productividad {z.tier.toLowerCase()}</span>
                  <span style={{ fontWeight: 700 }}>{z.pct}%</span>
                </div>
              ))}
            </div>
          </Card>
          <Card title="Ganancia por cultivo" sub="$ por hectárea">
            <BarsH max={900} suffix="" rows={[
              { label: "Trigo", value: 210, color: "#3a6b22" },
              { label: "Girasol", value: 95, color: "#3a6b22" },
              { label: "Maíz", value: 540, color: "#7ba83c" },
              { label: "Trigo", value: 410, color: "#7ba83c" },
            ]} />
          </Card>
        </div>
      </div>
    </Page>
  );
}

/* ---------------- NOTIFICACIONES ---------------- */
const NOTES = [
  { group: "Hoy", items: [
    { id: "n1", unread: true, icon: Icons.drop, color: "#c0492f", bg: "rgba(200,90,60,0.13)", title: "Estrés hídrico detectado en Lote Este", time: "08:12", sub: "La humedad del suelo cayó a 33% — se recomienda priorizar ese lote" },
    { id: "n2", unread: true, icon: Icons.bug, color: "#b58a16", bg: "rgba(214,170,40,0.16)", title: "Roya de la hoja en Potrero Oeste al 71%", time: "07:40", sub: "Se aconseja monitoreo y fungicida si supera umbral" },
    { id: "n3", unread: true, icon: Icons.spark, color: "#4f8a2f", bg: "rgba(123,180,60,0.15)", title: "Modelo de rendimiento IA actualizado", time: "06:00", sub: "Pronóstico revisado a 1.284 t (+6%)" },
  ]},
  { group: "Antes esta semana", items: [
    { id: "n4", unread: false, icon: Icons.rain, color: "#3f7fb0", bg: "rgba(63,127,176,0.13)", title: "Frente de lluvia previsto para el jueves", time: "Mar", sub: "80% de probabilidad · ~19 mm — retén la aplicación de nitrógeno" },
    { id: "n5", unread: false, icon: Icons.truck, color: "#6f7a52", bg: "#eceede", title: "210 t de trigo despachadas", time: "Lun", sub: "Almacén liberado al 71% de capacidad" },
  ]},
];

function NotificationsTab() {
  const initialUnread = NOTES.reduce((s, g) => s + g.items.filter((i) => i.unread).length, 0);
  const [read, setRead] = mState({});
  const markedCount = NOTES.reduce((s, g) => s + g.items.filter((i) => i.unread && read[i.id]).length, 0);
  const remaining = initialUnread - markedCount;

  mEffect(() => { if (window.HARV) window.HARV.setUnread(remaining); }, [remaining]);

  const markOne = (it) => { if (it.unread && !read[it.id]) setRead((r) => ({ ...r, [it.id]: true })); };
  const markAll = () => {
    const all = {};
    NOTES.forEach((g) => g.items.forEach((i) => { if (i.unread) all[i.id] = true; }));
    setRead(all);
    window.toast("Todas las notificaciones marcadas como leídas");
  };

  return (
    <Page>
      <Topbar title="Notificaciones" subtitle={`${remaining} sin leer · alertas, IA y operaciones`} range="Todas" searchPlaceholder="Buscar…" />
      <div style={{ maxWidth: 820 }}>
        <div style={{ display: "flex", justifyContent: "flex-end", marginBottom: 12 }}>
          <button onClick={markAll} disabled={remaining === 0} className="pill" style={{ border: "none", background: remaining === 0 ? "#e2e4d6" : "var(--lime)", color: "var(--ink)", fontFamily: "Onest", fontWeight: 600, fontSize: 13, padding: "8px 15px", cursor: remaining === 0 ? "default" : "pointer", display: "inline-flex", alignItems: "center", gap: 6, opacity: remaining === 0 ? 0.6 : 1 }}>
            <Icons.check size={15} /> Marcar todas como leídas
          </button>
        </div>
        {NOTES.map((g) => (
          <div key={g.group} style={{ marginBottom: 20 }}>
            <div style={{ fontSize: 12.5, fontWeight: 700, color: "var(--muted)", letterSpacing: "0.04em", marginBottom: 10 }}>{g.group.toUpperCase()}</div>
            <Card pad={8}>
              {g.items.map((n, i) => {
                const isUnread = n.unread && !read[n.id];
                return (
                  <div key={n.id} onClick={() => markOne(n)} style={{ display: "flex", alignItems: "flex-start", gap: 14, padding: "14px 14px", borderBottom: i < g.items.length - 1 ? "1px solid rgba(0,0,0,0.05)" : "none", cursor: n.unread ? "pointer" : "default", background: isUnread ? "rgba(198,232,75,0.07)" : "transparent", borderRadius: 10 }}>
                    <div style={{ width: 40, height: 40, borderRadius: 12, background: n.bg, color: n.color, flex: "none", display: "flex", alignItems: "center", justifyContent: "center" }}><n.icon size={20} /></div>
                    <div style={{ flex: 1, minWidth: 0 }}>
                      <div style={{ display: "flex", justifyContent: "space-between", gap: 10, alignItems: "center" }}>
                        <span style={{ fontSize: 14.5, fontWeight: 600, display: "flex", alignItems: "center", gap: 8 }}>
                          {isUnread && <span style={{ width: 8, height: 8, borderRadius: 999, background: "var(--lime-deep)", flex: "none" }} />}
                          {n.title}
                        </span>
                        <span style={{ fontSize: 12, color: "var(--muted)", flex: "none" }}>{n.time}</span>
                      </div>
                      <div style={{ fontSize: 13, color: "var(--muted)", marginTop: 3 }}>{n.sub}</div>
                    </div>
                  </div>
                );
              })}
            </Card>
          </div>
        ))}
      </div>
    </Page>
  );
}

/* ---------------- AJUSTES ---------------- */
function Toggle({ id, on }) {
  const key = "harvesta_set_" + id;
  const [v, setV] = mState(() => {
    const s = localStorage.getItem(key);
    return s == null ? on : s === "1";
  });
  const toggle = () => { const nv = !v; setV(nv); localStorage.setItem(key, nv ? "1" : "0"); };
  return (
    <div onClick={toggle} style={{ width: 44, height: 26, borderRadius: 999, background: v ? "var(--lime-deep)" : "#cfd2c2",
      padding: 3, cursor: "pointer", transition: "background 0.2s", flex: "none" }}>
      <div style={{ width: 20, height: 20, borderRadius: 999, background: "#fff", transform: v ? "translateX(18px)" : "none", transition: "transform 0.2s", boxShadow: "0 1px 3px rgba(0,0,0,0.2)" }} />
    </div>
  );
}
function SettingsTab() {
  const rows = [
    { g: "Preferencias", items: [["unit", "Unidades", "Métrico (ha, t, mm)", null], ["lang", "Idioma", "Español", null], ["theme", "Tema", "Claro", null]] },
    { g: "Alertas", items: [["a1", "Alertas de estrés hídrico", "Avisar bajo 40% de humedad", true], ["a2", "Alertas de riesgo de enfermedad", "Avisar sobre 70% de riesgo", true], ["a3", "Informe semanal de rendimiento", "Cada lunes 06:00", false]] },
    { g: "Integraciones", items: [["i1", "Imágenes Sentinel-2", "Conectado · 10 m, cada 3 días", true], ["i2", "API de clima", "Conectado · cada hora", true], ["i3", "Red de sondas de suelo", "9 sondas en línea", true]] },
  ];
  return (
    <Page>
      <Topbar title="Ajustes" subtitle="Cuenta, alertas y fuentes de datos" range="" searchPlaceholder="Buscar…" />
      <div style={{ maxWidth: 820, display: "flex", flexDirection: "column", gap: 18 }}>
        {rows.map((sec) => (
          <Card key={sec.g} title={sec.g}>
            <div style={{ display: "flex", flexDirection: "column" }}>
              {sec.items.map(([id, t, s, tog], i) => (
                <div key={id} onClick={tog === null ? () => window.toast(`${t}: ${s}`, "info") : undefined}
                  style={{ display: "flex", alignItems: "center", gap: 14, padding: "14px 2px", borderBottom: i < sec.items.length - 1 ? "1px solid rgba(0,0,0,0.05)" : "none", cursor: tog === null ? "pointer" : "default" }}>
                  <div style={{ flex: 1 }}>
                    <div style={{ fontSize: 14.5, fontWeight: 600 }}>{t}</div>
                    <div style={{ fontSize: 12.5, color: "var(--muted)", marginTop: 2 }}>{s}</div>
                  </div>
                  {tog === null ? <Icons.chevronDown size={18} /> : <Toggle id={id} on={tog} />}
                </div>
              ))}
            </div>
          </Card>
        ))}
      </div>
    </Page>
  );
}

/* ---------------- AYUDA ---------------- */
function HelpTab() {
  const [search, setSearch] = mState("");
  const topics = [
    [Icons.ndvi, "Entender el NDVI", "Cómo los índices de vegetación mapean el vigor y el potencial de rendimiento", "Explícame qué es el NDVI y cómo se interpreta en mis campos."],
    [Icons.drop, "Zonas de riego", "Define umbrales y automatiza el calendario por zona", "¿Cómo configuro las zonas de riego y sus umbrales?"],
    [Icons.bug, "Modelos de riesgo de enfermedad", "Cómo el clima + las imágenes impulsan el índice de riesgo", "¿Cómo funcionan los modelos de riesgo de enfermedad?"],
    [Icons.target, "Zonas de productividad", "Crea mapas de tasa variable a partir del histórico de desempeño", "¿Cómo creo mapas de tasa variable con las zonas de productividad?"],
    [Icons.layers, "Conectar campos", "Importa límites y fuentes satelitales", "¿Cómo conecto y configuro mis campos?"],
    [Icons.spark, "Agrónomo IA", "Haz preguntas y actúa sobre las recomendaciones", "¿Qué puede hacer el Agrónomo IA por mí?"],
  ];
  const list = topics.filter(([, t, s]) => !search.trim() || (t + " " + s).toLowerCase().includes(search.trim().toLowerCase()));
  return (
    <Page>
      <Topbar title="Centro de ayuda" subtitle="Guías, documentación y soporte" range="" searchPlaceholder="Buscar ayuda…" onSearch={setSearch} />
      <div style={{ maxWidth: 920 }}>
        <div style={{ background: "var(--olive-dark)", borderRadius: 22, padding: "28px 30px", color: "#f2f3ea", marginBottom: 20, position: "relative", overflow: "hidden" }}>
          <div style={{ position: "absolute", right: -20, top: -30, width: 160, height: 160, borderRadius: 999, background: "radial-gradient(circle, rgba(198,232,75,0.22), transparent 70%)" }} />
          <div style={{ fontSize: 22, fontWeight: 700, marginBottom: 6 }}>¿Cómo podemos ayudarte?</div>
          <div style={{ fontSize: 14, color: "rgba(255,255,255,0.7)", marginBottom: 18 }}>Busca en la documentación o pregunta directamente al Agrónomo IA.</div>
          <div style={{ display: "flex", gap: 12 }}>
            <div className="pill" style={{ flex: 1, display: "flex", alignItems: "center", gap: 10, background: "rgba(255,255,255,0.12)", padding: "12px 16px", fontSize: 14, color: "#f2f3ea" }}>
              <Icons.search size={17} />
              <input value={search} onChange={(e) => setSearch(e.target.value)} placeholder="Buscar artículos de ayuda…" style={{ flex: 1, border: "none", background: "transparent", outline: "none", fontFamily: "Onest", fontSize: 14, color: "#f2f3ea" }} />
            </div>
            <button onClick={() => window.askAI()} className="btn-lime" style={{ display: "flex", alignItems: "center", gap: 8, padding: "0 20px", borderRadius: 999, fontSize: 14 }}><Icons.spark size={17} /> Preguntar IA</button>
          </div>
        </div>
        <div style={{ display: "grid", gridTemplateColumns: "repeat(3,1fr)", gap: 16 }}>
          {list.map(([Ico, t, s, q]) => (
            <div key={t} onClick={() => window.askAI(q)} style={{ background: "var(--cream)", borderRadius: 18, padding: 20, boxShadow: "var(--shadow-card)", cursor: "pointer" }}>
              <div style={{ width: 40, height: 40, borderRadius: 12, background: "#eceede", color: "var(--ink-2)", display: "flex", alignItems: "center", justifyContent: "center", marginBottom: 14 }}><Ico size={20} /></div>
              <div style={{ fontSize: 15.5, fontWeight: 700, marginBottom: 5 }}>{t}</div>
              <div style={{ fontSize: 13, color: "var(--muted)", lineHeight: 1.45 }}>{s}</div>
            </div>
          ))}
        </div>
        {list.length === 0 && <div style={{ padding: "20px 4px", fontSize: 14, color: "var(--muted)" }}>Sin artículos para “{search}”.</div>}
      </div>
    </Page>
  );
}

Object.assign(window, { InventoryTab, ReportsTab, NotificationsTab, SettingsTab, HelpTab });
