/* global React, Icons */
const { useState: uState, useEffect: uEffect, useRef: uRef } = React;

const NAV_MAIN = [
  ["dashboard", "Panel"], ["field", "Campos"], ["truck", "Flota"], ["irrigation", "Riego"],
  ["climate", "Clima"], ["pests", "Plagas"], ["flask", "Químicos"], ["inventory", "Inventario"],
  ["reports", "Informes"], ["help", "Ayuda"],
];
// clave de ruta por etiqueta
const ROUTE = { "Panel": "dashboard", "Campos": "fields", "Flota": "fleet", "Riego": "irrigation",
  "Clima": "climate", "Plagas": "pests", "Químicos": "chemicals", "Inventario": "inventory", "Informes": "reports",
  "Ayuda": "help", "Notificaciones": "notifications", "Ajustes": "settings" };

const Logo = () => (
  <svg width="36" height="36" viewBox="0 0 40 40" fill="none">
    <rect width="40" height="40" rx="11" fill="#2d3122" />
    <path d="M11 10 H29 V16 H17 V30 H11 Z" fill="#c6e84b" />
    <path d="M29 30 V12 H23 V24 H13 V30 Z" fill="#f2f3ea" />
  </svg>
);

// Iniciales para el avatar a partir del nombre completo o, si no hay, del correo.
function userInitials(user) {
  const label = (user && (user.user_metadata?.full_name || user.email)) || "";
  if (!label) return "IC";
  const base = label.split("@")[0].replace(/[._-]+/g, " ").trim();
  const parts = base.split(" ").filter(Boolean);
  if (parts.length >= 2) return (parts[0][0] + parts[1][0]).toUpperCase();
  return (base.slice(0, 2) || "IC").toUpperCase();
}

function Sidebar({ route, go, user, onLogout }) {
  const isActive = (label) => ROUTE[label] === route;
  const [unread, setUnread] = uState(window.HARV ? window.HARV.getUnread() : 3);
  const [menuOpen, setMenuOpen] = uState(false);
  const menuRef = uRef(null);
  uEffect(() => {
    const h = (e) => setUnread(e.detail);
    window.addEventListener("harvesta:unread", h);
    return () => window.removeEventListener("harvesta:unread", h);
  }, []);
  uEffect(() => {
    const h = (e) => { if (menuRef.current && !menuRef.current.contains(e.target)) setMenuOpen(false); };
    document.addEventListener("mousedown", h);
    return () => document.removeEventListener("mousedown", h);
  }, []);
  const email = user?.email || "demo@pampago.local";
  const fullName = user?.user_metadata?.full_name || "Ing. de campo";
  return (
    <div style={{ position: "absolute", left: 0, top: 0, width: 248, height: 940,
      background: "var(--cream)", display: "flex", flexDirection: "column",
      padding: "30px 18px 24px", borderRight: "1px solid rgba(0,0,0,0.04)", zIndex: 5 }}>
      <div style={{ display: "flex", alignItems: "center", gap: 10, padding: "0 8px", marginBottom: 30 }}>
        <Logo />
        <span style={{ fontSize: 20, fontWeight: 700, letterSpacing: "-0.02em" }}>Pampa Go</span>
      </div>
      <div style={{ fontSize: 11, fontWeight: 600, color: "var(--muted-2)", letterSpacing: "0.08em", padding: "0 10px 8px" }}>MENÚ</div>
      <div style={{ display: "flex", flexDirection: "column", gap: 3 }}>
        {NAV_MAIN.map(([ico, label]) => {
          const Ico = Icons[ico];
          return (
            <div key={label} className={"nav-item" + (isActive(label) ? " active" : "")}
                 onClick={() => go(ROUTE[label])}>
              <span className="nav-ico"><Ico size={18} /></span>{label}
            </div>
          );
        })}
      </div>
      <div style={{ marginTop: "auto", display: "flex", flexDirection: "column", gap: 3 }}>
        <div className={"nav-item" + (route === "notifications" ? " active" : "")} onClick={() => go("notifications")}>
          <span className="nav-ico" style={{ position: "relative" }}>
            <Icons.bell size={18} />{unread > 0 && <span className="badge" style={{ top: -5, right: -5 }}>{unread}</span>}
          </span>Notificaciones
        </div>
        <div className={"nav-item" + (route === "settings" ? " active" : "")} onClick={() => go("settings")}>
          <span className="nav-ico"><Icons.settings size={18} /></span>Ajustes
        </div>
        <div ref={menuRef} style={{ position: "relative", marginTop: 6, paddingTop: 12, borderTop: "1px solid rgba(0,0,0,0.06)" }}>
          <div className="row-hover" onClick={() => setMenuOpen((o) => !o)}
            style={{ display: "flex", alignItems: "center", gap: 12, padding: "6px 8px", borderRadius: 12, cursor: "pointer" }}>
            <span style={{ width: 38, height: 38, borderRadius: 999, flex: "none", background: "var(--lime)", color: "var(--ink)",
              display: "flex", alignItems: "center", justifyContent: "center", fontSize: 14, fontWeight: 700 }}>
              {userInitials(user)}
            </span>
            <div style={{ lineHeight: 1.2, flex: 1, minWidth: 0 }}>
              <div style={{ fontSize: 14.5, fontWeight: 600, whiteSpace: "nowrap", overflow: "hidden", textOverflow: "ellipsis" }}>{fullName}</div>
              <div style={{ fontSize: 12, color: "var(--muted)", whiteSpace: "nowrap", overflow: "hidden", textOverflow: "ellipsis" }}>{email}</div>
            </div>
            <span style={{ flex: "none", color: "var(--muted)", display: "flex", transform: menuOpen ? "rotate(180deg)" : "none", transition: "transform 0.15s ease" }}>
              <Icons.chevronDown size={16} />
            </span>
          </div>

          {menuOpen && (
            <div className="card" style={{ position: "absolute", bottom: "calc(100% + 8px)", left: 0, right: 0, padding: 6, zIndex: 20 }}>
              <button type="button" onClick={() => { setMenuOpen(false); onLogout && onLogout(); }}
                style={{ width: "100%", display: "flex", alignItems: "center", gap: 10, padding: "10px 12px", borderRadius: 12,
                  border: "none", background: "transparent", cursor: "pointer", fontFamily: "inherit", fontSize: 13.5, fontWeight: 600, color: "#c0492f" }}
                onMouseEnter={(e) => (e.currentTarget.style.background = "rgba(192,73,47,0.08)")}
                onMouseLeave={(e) => (e.currentTarget.style.background = "transparent")}>
                <Icons.logout size={17} /> Cerrar sesión
              </button>
            </div>
          )}
        </div>
      </div>
    </div>
  );
}

const RANGES = ["Hoy", "Esta semana", "Este mes", "Esta temporada"];

// Barra superior para las pestañas de datos
function Topbar({ title, subtitle, range = "Esta semana", onSearch, searchPlaceholder = "Buscar campos…" }) {
  const [q, setQ] = uState("");
  const [rangeLbl, setRangeLbl] = uState(range);
  const [menu, setMenu] = uState(false);
  const wrap = uRef(null);
  uEffect(() => { setRangeLbl(range); }, [range]);
  uEffect(() => {
    const h = (e) => { if (wrap.current && !wrap.current.contains(e.target)) setMenu(false); };
    document.addEventListener("mousedown", h);
    return () => document.removeEventListener("mousedown", h);
  }, []);
  const onType = (e) => { setQ(e.target.value); if (onSearch) onSearch(e.target.value); };
  return (
    <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between", marginBottom: 24 }}>
      <div>
        <h1 style={{ fontSize: 27, fontWeight: 800, letterSpacing: "-0.02em", lineHeight: 1.1, whiteSpace: "nowrap" }}>{title}</h1>
        <div style={{ fontSize: 14, color: "var(--muted)", marginTop: 4 }}>{subtitle}</div>
      </div>
      <div style={{ display: "flex", alignItems: "center", gap: 12 }}>
        <div className="pill" style={{ display: "flex", alignItems: "center", gap: 9, background: "var(--cream)",
          padding: "9px 14px", fontSize: 13.5, color: "var(--muted)", boxShadow: "var(--shadow-soft)" }}>
          <Icons.search size={16} />
          <input value={q} onChange={onType} placeholder={searchPlaceholder}
            style={{ border: "none", background: "transparent", outline: "none", fontFamily: "Onest", fontSize: 13.5, color: "var(--ink)", width: 124 }} />
        </div>
        <div ref={wrap} style={{ position: "relative" }}>
          <div onClick={() => setMenu((m) => !m)} className="pill" style={{ display: "flex", alignItems: "center", gap: 9, background: "var(--cream)",
            padding: "9px 14px", fontSize: 13.5, fontWeight: 600, boxShadow: "var(--shadow-soft)", whiteSpace: "nowrap", cursor: "pointer" }}>
            <Icons.calendar size={16} /> {rangeLbl} <Icons.chevronDown size={15} />
          </div>
          {menu && (
            <div style={{ position: "absolute", right: 0, top: "calc(100% + 8px)", background: "var(--cream)", borderRadius: 14,
              boxShadow: "var(--shadow-card)", padding: 6, zIndex: 30, minWidth: 168, border: "1px solid rgba(0,0,0,0.05)" }}>
              {RANGES.map((r) => (
                <div key={r} onClick={() => { setRangeLbl(r); setMenu(false); }}
                  style={{ display: "flex", alignItems: "center", justifyContent: "space-between", gap: 10, padding: "9px 12px", borderRadius: 9,
                    fontSize: 13.5, fontWeight: r === rangeLbl ? 700 : 500, color: r === rangeLbl ? "var(--ink)" : "var(--ink-2)", cursor: "pointer" }}
                  onMouseEnter={(e) => (e.currentTarget.style.background = "#f0f1e8")}
                  onMouseLeave={(e) => (e.currentTarget.style.background = "transparent")}>
                  {r} {r === rangeLbl && <Icons.check size={15} />}
                </div>
              ))}
            </div>
          )}
        </div>
        <button onClick={() => window.askAI()} className="btn-lime" style={{ display: "flex", alignItems: "center", gap: 8, padding: "10px 18px", borderRadius: 999, fontSize: 14, whiteSpace: "nowrap" }}>
          <Icons.spark size={17} /> Preguntar IA
        </button>
      </div>
    </div>
  );
}

// Tarjeta genérica con encabezado opcional
function Card({ title, sub, action, children, style, pad = 22, dark }) {
  return (
    <div style={{ background: dark ? "var(--olive-dark)" : "var(--cream)", borderRadius: 22,
      boxShadow: "var(--shadow-card)", padding: pad, color: dark ? "#f2f3ea" : "var(--ink)", ...style }}>
      {(title || action) && (
        <div style={{ display: "flex", justifyContent: "space-between", alignItems: "flex-start", marginBottom: 16 }}>
          <div>
            {title && <div style={{ fontSize: 17, fontWeight: 700 }}>{title}</div>}
            {sub && <div style={{ fontSize: 13, color: dark ? "rgba(255,255,255,0.55)" : "var(--muted)", marginTop: 2 }}>{sub}</div>}
          </div>
          {action}
        </div>
      )}
      {children}
    </div>
  );
}

// Tarjeta KPI
function KPI({ icon: Ico, label, value, unit, delta, deltaGood, spark, sparkColor }) {
  const up = delta != null && delta >= 0;
  const good = deltaGood != null ? deltaGood : up;
  return (
    <div style={{ background: "var(--cream)", borderRadius: 20, padding: "18px 20px", boxShadow: "var(--shadow-card)",
      display: "flex", flexDirection: "column", gap: 14, minWidth: 0 }}>
      <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center" }}>
        <div style={{ width: 40, height: 40, borderRadius: 12, background: "#eceede",
          display: "flex", alignItems: "center", justifyContent: "center", color: "var(--ink-2)" }}><Ico size={20} /></div>
        {delta != null && (
          <span style={{ display: "inline-flex", alignItems: "center", gap: 3, fontSize: 13, fontWeight: 700,
            color: good ? "#4f8a2f" : "#c0492f", background: good ? "rgba(123,180,60,0.14)" : "rgba(200,90,60,0.13)",
            padding: "3px 9px", borderRadius: 999 }}>
            {up ? <Icons.trendUp size={13} /> : <Icons.trendDown size={13} />}{Math.abs(delta)}%
          </span>
        )}
      </div>
      <div>
        <div style={{ fontSize: 12.5, color: "var(--muted)", fontWeight: 500 }}>{label}</div>
        <div style={{ display: "flex", alignItems: "baseline", gap: 4, marginTop: 2, whiteSpace: "nowrap" }}>
          <span style={{ fontSize: 28, fontWeight: 800, letterSpacing: "-0.02em" }}>{value}</span>
          {unit && <span style={{ fontSize: 14, color: "var(--muted)", fontWeight: 600 }}>{unit}</span>}
        </div>
      </div>
      {spark && <div style={{ marginTop: -4 }}><window.Spark data={spark} color={sparkColor || "#3a6b22"} width={200} height={32} /></div>}
    </div>
  );
}

// Panel insignia del Agrónomo IA
function AIInsight({ insight, style }) {
  return (
    <div style={{ background: "var(--olive-dark)", borderRadius: 22, padding: 22, color: "#f2f3ea",
      boxShadow: "var(--shadow-card)", position: "relative", overflow: "hidden", ...style }}>
      <div style={{ position: "absolute", right: -30, top: -30, width: 140, height: 140, borderRadius: 999,
        background: "radial-gradient(circle, rgba(198,232,75,0.22), transparent 70%)" }} />
      <div style={{ display: "flex", alignItems: "center", gap: 10, marginBottom: 14 }}>
        <div style={{ width: 34, height: 34, borderRadius: 10, background: "var(--lime)", color: "var(--ink)",
          display: "flex", alignItems: "center", justifyContent: "center" }}><Icons.spark size={19} /></div>
        <div style={{ lineHeight: 1.25 }}>
          <div style={{ fontSize: 14.5, fontWeight: 700, whiteSpace: "nowrap" }}>Agrónomo IA</div>
          <div style={{ fontSize: 11.5, color: "var(--lime)", fontWeight: 600 }}>{insight.tag}</div>
        </div>
      </div>
      <div style={{ fontSize: 14.5, lineHeight: 1.5, color: "rgba(255,255,255,0.86)" }}>{insight.text}</div>
      <button onClick={() => window.askAI(`${insight.tag}: ${insight.action}. ¿Qué me recomiendas y cuáles son los próximos pasos?`)}
        style={{ marginTop: 16, display: "inline-flex", alignItems: "center", gap: 7, background: "rgba(255,255,255,0.1)",
        color: "#f2f3ea", border: "none", fontFamily: "Onest", fontWeight: 600, fontSize: 13.5, padding: "9px 15px",
        borderRadius: 999, cursor: "pointer" }}>
        {insight.action} <Icons.arrowRight size={15} />
      </button>
    </div>
  );
}

function StatusBadge({ status }) {
  const s = window.STATUS[status];
  return (
    <span style={{ display: "inline-flex", alignItems: "center", gap: 6, fontSize: 12.5, fontWeight: 600,
      color: s.color, background: s.bg, padding: "4px 11px", borderRadius: 999, whiteSpace: "nowrap" }}>
      <span style={{ width: 7, height: 7, borderRadius: 999, background: s.color }} />{s.label}
    </span>
  );
}

// Contenedor de página para las pestañas de datos (área desplazable)
function Page({ children }) {
  return (
    <div id="tabscroll" style={{ position: "absolute", left: 248, top: 0, width: 1192, height: 940, overflowY: "auto",
      background: "#eceee4", padding: "30px 34px 40px" }}>
      {children}
    </div>
  );
}

Object.assign(window, { Sidebar, Topbar, Card, KPI, AIInsight, StatusBadge, Page });
