/* global React, Icons, FIELDS, FIELD_INFO, HARVEST, HARVEST_INFO, STATUS, StatusBadge */
const { useState: detState, useEffect: detEffect } = React;

const money = (n) => "$" + Number(n).toLocaleString("es-ES");

function DRow({ label, value, strong }) {
  return (
    <div style={{ display: "flex", justifyContent: "space-between", alignItems: "baseline", gap: 14, padding: "10px 0", borderBottom: "1px solid rgba(0,0,0,0.05)" }}>
      <span style={{ fontSize: 13, color: "var(--muted)", whiteSpace: "nowrap" }}>{label}</span>
      <span style={{ fontSize: 13.5, fontWeight: strong ? 700 : 600, textAlign: "right" }}>{value}</span>
    </div>
  );
}

function SectionTitle({ children }) {
  return <div style={{ fontSize: 12, fontWeight: 700, color: "var(--muted-2)", letterSpacing: "0.07em", margin: "22px 0 4px" }}>{children}</div>;
}

function Metric({ label, value, unit, color }) {
  return (
    <div style={{ background: "var(--cream)", borderRadius: 14, padding: "13px 15px", boxShadow: "var(--shadow-soft)" }}>
      <div style={{ fontSize: 11.5, color: "var(--muted)", fontWeight: 500 }}>{label}</div>
      <div style={{ display: "flex", alignItems: "baseline", gap: 3, marginTop: 3 }}>
        <span style={{ fontSize: 21, fontWeight: 800, letterSpacing: "-0.02em", color: color || "var(--ink)" }}>{value}</span>
        {unit && <span style={{ fontSize: 12.5, color: "var(--muted)", fontWeight: 600 }}>{unit}</span>}
      </div>
    </div>
  );
}

function Drawer({ tag, title, subtitle, children, footer, onClose }) {
  return (
    <div style={{ position: "absolute", inset: 0, zIndex: 60 }}>
      <div onClick={onClose} style={{ position: "absolute", inset: 0, background: "rgba(20,28,10,0.34)", backdropFilter: "blur(2px)" }} />
      <div style={{ position: "absolute", right: 0, top: 0, width: 480, height: 940, background: "#eceee4", boxShadow: "-30px 0 70px -30px rgba(30,40,15,0.6)", display: "flex", flexDirection: "column", animation: "harvSlide .32s cubic-bezier(.2,.8,.2,1)" }}>
        <div style={{ background: "var(--olive-dark)", color: "#f2f3ea", padding: "20px 22px 20px", position: "relative", overflow: "hidden", flex: "none" }}>
          <div style={{ position: "absolute", right: -24, top: -28, width: 130, height: 130, borderRadius: 999, background: "radial-gradient(circle, rgba(198,232,75,0.24), transparent 70%)" }} />
          <div style={{ display: "flex", alignItems: "flex-start", gap: 12 }}>
            <div style={{ flex: 1 }}>
              {tag && <div style={{ fontSize: 11.5, color: "var(--lime)", fontWeight: 700, letterSpacing: "0.04em", marginBottom: 6 }}>{tag}</div>}
              <div style={{ fontSize: 22, fontWeight: 800, letterSpacing: "-0.02em" }}>{title}</div>
              {subtitle && <div style={{ fontSize: 13, color: "rgba(255,255,255,0.66)", marginTop: 4 }}>{subtitle}</div>}
            </div>
            <button onClick={onClose} 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", flex: "none" }}>
              <Icons.close size={18} />
            </button>
          </div>
        </div>
        <div style={{ flex: 1, overflowY: "auto", padding: "4px 22px 24px" }}>{children}</div>
        {footer && <div style={{ flex: "none", padding: "14px 22px 18px", background: "var(--cream)", borderTop: "1px solid rgba(0,0,0,0.06)" }}>{footer}</div>}
      </div>
    </div>
  );
}

function AskButton({ seed, onClose }) {
  return (
    <button onClick={() => { onClose(); window.askAI(seed); }} className="btn-lime" style={{ width: "100%", display: "flex", alignItems: "center", justifyContent: "center", gap: 8, padding: "13px", borderRadius: 14, fontSize: 14.5 }}>
      <Icons.spark size={18} /> Preguntar al Agrónomo IA
    </button>
  );
}

function FieldDetail({ field, onClose }) {
  const info = FIELD_INFO[field.id] || {};
  const s = STATUS[field.status];
  const trendUp = field.change >= 0;
  return (
    <Drawer tag={`${field.zone} · ${field.id}`} title={field.name} subtitle={`${field.crop} · ${field.area} ha`} onClose={onClose}
      footer={<AskButton onClose={onClose} seed={`Cuéntame sobre el ${field.name} (${field.crop}): estado ${s.label}, NDVI ${field.ndvi}, humedad ${field.moisture}%. ${info.obs || ""} ¿Qué me recomiendas?`} />}>
      <div style={{ display: "flex", alignItems: "center", gap: 10, margin: "16px 0 6px" }}>
        <StatusBadge status={field.status} />
        <span style={{ fontSize: 13, fontWeight: 700, color: trendUp ? "#4f8a2f" : "#c0492f", display: "inline-flex", alignItems: "center", gap: 4 }}>
          {trendUp ? <Icons.trendUp size={14} /> : <Icons.trendDown size={14} />}{Math.abs(field.change)}% vs. sem. pasada
        </span>
      </div>
      <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr 1fr", gap: 10, marginTop: 12 }}>
        <Metric label="NDVI" value={field.ndvi.toFixed(2)} color={field.ndvi > 0.55 ? "#4f8a2f" : field.ndvi > 0.42 ? "#b58a16" : "#c0492f"} />
        <Metric label="Humedad" value={field.moisture} unit="%" color={field.moisture >= 50 ? "#4f8a2f" : "#c0492f"} />
        <Metric label="Rendim." value={field.yieldPred} unit={field.unit} />
      </div>

      {info.ndviTrend && (
        <div style={{ background: "var(--cream)", borderRadius: 16, padding: "16px 18px", boxShadow: "var(--shadow-soft)", marginTop: 12 }}>
          <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center", marginBottom: 8 }}>
            <span style={{ fontSize: 13.5, fontWeight: 700 }}>Tendencia NDVI</span>
            <span style={{ fontSize: 12, color: "var(--muted)" }}>últimas 6 sem.</span>
          </div>
          <window.Spark data={info.ndviTrend} color={field.ndvi > 0.45 ? "#3a6b22" : "#c0492f"} width={416} height={44} />
        </div>
      )}

      <SectionTitle>CULTIVO</SectionTitle>
      <DRow label="Variedad" value={info.variety || "—"} />
      <DRow label="Fecha de siembra" value={info.plantedOn || "—"} />
      <DRow label="Etapa fenológica" value={info.stage || "—"} />
      <DRow label="Cosecha estimada" value={info.harvestEta || "—"} />
      <DRow label="Densidad" value={info.density || "—"} />
      <DRow label="Tipo de suelo" value={info.soil || "—"} />

      <SectionTitle>ÚLTIMA ACTIVIDAD</SectionTitle>
      <DRow label="Último riego" value={info.lastIrrigation || "—"} />
      <DRow label="Última aplicación" value={info.lastSpray || "—"} />

      {info.obs && (
        <div style={{ marginTop: 18, background: field.status === "stress" ? "rgba(200,90,60,0.1)" : field.status === "watch" ? "rgba(214,170,40,0.12)" : "rgba(123,180,60,0.12)", borderRadius: 14, padding: "14px 16px", display: "flex", gap: 11 }}>
          <span style={{ color: s.color, flex: "none", marginTop: 1 }}><Icons.alert size={18} /></span>
          <div style={{ fontSize: 13.5, lineHeight: 1.5, color: "var(--ink-2)" }}>{info.obs}</div>
        </div>
      )}
    </Drawer>
  );
}

function HarvestDetail({ crop, onClose }) {
  const h = HARVEST.find((x) => x.crop === crop);
  const info = HARVEST_INFO[crop] || {};
  if (!h) return null;
  const pct = Math.round((h.amount / h.cap) * 100);
  return (
    <Drawer tag="Grano almacenado" title={crop} subtitle={`${info.silo || "Almacén"} · ${info.grade || ""}`} onClose={onClose}
      footer={<AskButton onClose={onClose} seed={`Tengo ${h.amount} t de ${crop} en ${info.silo} (humedad media ${info.avgMoisture != null ? info.avgMoisture + "%" : "n/a"}, destino ${info.destination}). ¿Cuándo y cómo conviene venderlo o despacharlo?`} />}>
      <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 10, marginTop: 16 }}>
        <Metric label="Almacenado" value={h.amount.toLocaleString("es-ES")} unit={`/ ${h.cap.toLocaleString("es-ES")} t`} />
        <Metric label="Ocupación silo" value={pct} unit="%" color={pct > 85 ? "#c0492f" : "#4f8a2f"} />
        <Metric label="Valor en stock" value={money(h.value)} />
        <Metric label="Precio referencia" value={info.pricePerT ? money(info.pricePerT) : "—"} unit={info.pricePerT ? "/ t" : ""} />
      </div>

      {info.avgMoisture != null && (
        <div style={{ background: "var(--cream)", borderRadius: 14, padding: "14px 16px", boxShadow: "var(--shadow-soft)", marginTop: 12 }}>
          <div style={{ display: "flex", justifyContent: "space-between", alignItems: "baseline", marginBottom: 8 }}>
            <span style={{ fontSize: 13.5, fontWeight: 700 }}>Humedad de almacenaje</span>
            <span style={{ fontSize: 13, fontWeight: 700, color: info.avgMoisture <= info.target ? "#4f8a2f" : "#c0492f" }}>{info.avgMoisture}% <span style={{ color: "var(--muted)", fontWeight: 500 }}>/ {info.target}% máx.</span></span>
          </div>
          <div style={{ height: 8, borderRadius: 5, background: "#e2e4d6", overflow: "hidden", position: "relative" }}>
            <div style={{ height: "100%", borderRadius: 5, width: `${(info.avgMoisture / 20) * 100}%`, background: info.avgMoisture <= info.target ? "#4f8a2f" : "#c0492f" }} />
            <div style={{ position: "absolute", top: -2, bottom: -2, left: `${(info.target / 20) * 100}%`, width: 2, background: "#1b1e14", opacity: 0.4 }} />
          </div>
        </div>
      )}

      <SectionTitle>TRAZABILIDAD DE INGRESOS</SectionTitle>
      <div style={{ background: "var(--cream)", borderRadius: 14, padding: "6px 14px", boxShadow: "var(--shadow-soft)" }}>
        <div style={{ display: "grid", gridTemplateColumns: "0.8fr 1.2fr 0.8fr 0.9fr", gap: 8, fontSize: 11, color: "var(--muted)", fontWeight: 600, padding: "10px 0 8px", borderBottom: "1px solid rgba(0,0,0,0.06)" }}>
          <span>FECHA</span><span>LOTE ORIGEN</span><span style={{ textAlign: "right" }}>TON.</span><span style={{ textAlign: "right" }}>HUM.</span>
        </div>
        {(info.entries || []).map((e, i) => (
          <div key={i} style={{ display: "grid", gridTemplateColumns: "0.8fr 1.2fr 0.8fr 0.9fr", gap: 8, alignItems: "center", fontSize: 13, padding: "11px 0", borderBottom: i < info.entries.length - 1 ? "1px solid rgba(0,0,0,0.04)" : "none" }}>
            <span style={{ color: "var(--muted)" }}>{e.date}</span>
            <span style={{ fontWeight: 600 }}>{e.field}</span>
            <span style={{ textAlign: "right", fontWeight: 700 }}>{e.tonnes}</span>
            <span style={{ textAlign: "right", color: "var(--muted)" }}>{e.moisture != null ? e.moisture + "%" : "—"}</span>
          </div>
        ))}
      </div>

      <SectionTitle>LOGÍSTICA</SectionTitle>
      <DRow label="Inicio de cosecha" value={info.harvestStart || "—"} />
      <DRow label="Fin de cosecha" value={info.harvestEnd && info.harvestEnd !== "—" ? info.harvestEnd : "En curso"} />
      <DRow label="Destino" value={info.destination || "—"} strong />

      {info.note && (
        <div style={{ marginTop: 18, background: "rgba(123,180,60,0.12)", borderRadius: 14, padding: "14px 16px", display: "flex", gap: 11 }}>
          <span style={{ color: "#4f8a2f", flex: "none", marginTop: 1 }}><Icons.checkCircle size={18} /></span>
          <div style={{ fontSize: 13.5, lineHeight: 1.5, color: "var(--ink-2)" }}>{info.note}</div>
        </div>
      )}
    </Drawer>
  );
}

function DetailLayer() {
  const [state, setState] = detState(null);
  detEffect(() => {
    const onField = (e) => { const f = FIELDS.find((x) => x.id === e.detail.id); if (f) setState({ type: "field", field: f }); };
    const onHarvest = (e) => setState({ type: "harvest", crop: e.detail.crop });
    const onKey = (e) => { if (e.key === "Escape") setState(null); };
    window.addEventListener("detail:field", onField);
    window.addEventListener("detail:harvest", onHarvest);
    window.addEventListener("keydown", onKey);
    return () => {
      window.removeEventListener("detail:field", onField);
      window.removeEventListener("detail:harvest", onHarvest);
      window.removeEventListener("keydown", onKey);
    };
  }, []);
  const close = () => setState(null);
  if (!state) return null;
  if (state.type === "field") return <FieldDetail field={state.field} onClose={close} />;
  if (state.type === "harvest") return <HarvestDetail crop={state.crop} onClose={close} />;
  return null;
}

window.openField = (id) => window.dispatchEvent(new CustomEvent("detail:field", { detail: { id } }));
window.openHarvest = (crop) => window.dispatchEvent(new CustomEvent("detail:harvest", { detail: { crop } }));
window.DetailLayer = DetailLayer;
