/* App shell — sidebar nav, top bar, mobile bottom nav */

const NAV = [
  { id: "today", label: "Hoy", icon: "home" },
  { id: "metrics", label: "Métricas", icon: "metrics" },
  { id: "activities", label: "Actividades", icon: "activity" },
  { id: "agents", label: "Coach", icon: "coach" },
  { id: "plans", label: "Planes", icon: "plan" },
  { id: "knowledge", label: "Biblioteca", icon: "book" },
  { id: "settings", label: "Configuración", icon: "settings" },
];

const Sidebar = ({ route, setRoute, density, onboardingActive, user, inDemo }) => {
  const name = inDemo ? "Demo" : (user?.name || (user?.email ? user.email.split("@")[0] : "usuario"));
  const initial = (name?.[0] || "·").toUpperCase();
  const sub = inDemo ? "modo demo" : (user?.email || "self-hosted");

  // Suscripción al singleton de uploads para mostrar un badge "N" sobre el ítem
  // "Biblioteca" cuando hay archivos procesando o pendientes (incluso si el
  // user está en otra ruta). Re-render por subscribe/notify.
  const [, setTick] = React.useState(0);
  React.useEffect(() => {
    if (typeof window === "undefined" || typeof window.__af_uploadQueue__?.subscribe !== "function") return undefined;
    return window.__af_uploadQueue__.subscribe(() => setTick((t) => t + 1));
  }, []);
  const uploadActive = (typeof window !== "undefined" && window.__af_uploadQueue__)
    ? window.__af_uploadQueue__.activeCount()
    : 0;

  return (
    <aside className="af-sidebar" style={{
      width: 220,
      flexShrink: 0,
      background: "var(--bg-1)",
      borderRight: "1px solid var(--line)",
      display: "flex", flexDirection: "column",
      padding: "var(--sp-5) var(--sp-4)",
    }}>
      <div className="af-sidebar-wordmark" style={{ display: "flex", alignItems: "center", gap: 8, marginBottom: "var(--sp-8)", padding: "0 4px" }}>
        <window.FtiMindLogo.Mark size={26} />
        <div className="af-sidebar-label" style={{ display: "flex", alignItems: "baseline", gap: 0 }}>
          <window.FtiMindLogo.Wordmark size={14} />
        </div>
        <span className="af-sidebar-version" style={{ fontSize: 9, color: "var(--text-3)", fontFamily: "var(--font-mono)", marginLeft: "auto" }}>v0.4</span>
      </div>

      <nav style={{ display: "flex", flexDirection: "column", gap: 2 }}>
        {NAV.map((n) => (
          <button
            key={n.id}
            onClick={() => setRoute(n.id)}
            className="af-sidebar-nav-btn"
            title={n.label}
            style={{
              display: "flex", alignItems: "center", gap: 10,
              padding: "8px 10px",
              border: "none",
              borderRadius: "var(--r-2)",
              background: route === n.id ? "var(--bg-3)" : "transparent",
              color: route === n.id ? "var(--text)" : "var(--text-2)",
              fontSize: 13, fontWeight: 500, textAlign: "left",
              transition: "all 0.15s",
            }}
            onMouseEnter={(e) => { if (route !== n.id) e.currentTarget.style.background = "var(--bg-2)"; }}
            onMouseLeave={(e) => { if (route !== n.id) e.currentTarget.style.background = "transparent"; }}
          >
            <Icon name={n.icon} size={15} />
            <span className="af-sidebar-label">{n.label}</span>
            {n.id === "knowledge" && uploadActive > 0 && (
              <span
                title={`${uploadActive} upload(s) en proceso`}
                style={{
                  marginLeft: "auto",
                  minWidth: 18, height: 18, padding: "0 5px",
                  borderRadius: 9,
                  background: "var(--info)",
                  color: "var(--bg)",
                  fontSize: 10, fontWeight: 600, fontFamily: "var(--font-mono)",
                  display: "grid", placeItems: "center",
                }}
              >
                {uploadActive}
              </span>
            )}
          </button>
        ))}
      </nav>

      <div style={{ flex: 1 }} />

      <div className="af-sidebar-privacy" style={{
        padding: "10px 12px",
        borderRadius: "var(--r-2)",
        background: "var(--bg-2)",
        border: "1px solid var(--line)",
        fontSize: 11,
      }}>
        <div style={{ display: "flex", alignItems: "center", gap: 6, marginBottom: 4 }}>
          <Icon name="lock" size={11} color="var(--good)" />
          <span style={{ color: "var(--good)", fontFamily: "var(--font-mono)", fontWeight: 500, fontSize: 10.5 }}>LOCAL</span>
          <span style={{ color: "var(--text-3)", marginLeft: "auto", fontFamily: "var(--font-mono)", fontSize: 9 }}>+ LLM cloud</span>
        </div>
        <div style={{ color: "var(--text-3)", fontSize: 10.5, lineHeight: 1.4 }}>
          Datos en tu NAS · LLM via OpenAI
        </div>
      </div>

      <div style={{ marginTop: 12, display: "flex", alignItems: "center", gap: 10, padding: "0 4px" }}>
        <div style={{
          width: 26, height: 26, borderRadius: "50%",
          background: "var(--accent)", color: "var(--accent-fg)",
          display: "grid", placeItems: "center",
          fontWeight: 600, fontSize: 11,
          flexShrink: 0,
        }}>{initial}</div>
        <div className="af-sidebar-user-text" style={{ minWidth: 0, flex: 1 }}>
          <div style={{ fontSize: 12, fontWeight: 500, lineHeight: 1.2, overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap" }}>{name}</div>
          <div style={{ fontSize: 10, color: "var(--text-3)", lineHeight: 1.2, overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap" }}>{sub}</div>
        </div>
      </div>
    </aside>
  );
};

const MobileNav = ({ route, setRoute }) => {
  const [open, setOpen] = React.useState(false);

  const goto = (id) => { setRoute(id); setOpen(false); };
  const current = NAV.find(n => n.id === route);

  return (
    <>
      {/* Top mobile bar with hamburger + current screen */}
      <div className="af-mobile-bar" style={{
        zIndex: 90,
        display: "none",
        alignItems: "center", gap: 10,
        flexShrink: 0,
        padding: "10px 14px",
        background: "color-mix(in srgb, var(--bg) 88%, transparent)",
        backdropFilter: "blur(10px)",
        WebkitBackdropFilter: "blur(10px)",
        borderBottom: "1px solid var(--line)",
      }}>
        <button onClick={() => setOpen(true)} aria-label="Abrir menú" style={{
          width: 36, height: 36, borderRadius: "var(--r-2)",
          border: "1px solid var(--line)",
          background: "var(--bg-1)", color: "var(--text)",
          display: "grid", placeItems: "center",
        }}>
          <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round">
            <path d="M3 6h18M3 12h18M3 18h18" />
          </svg>
        </button>
        <div style={{ display: "flex", alignItems: "center", gap: 8 }}>
          <window.FtiMindLogo.Mark size={22} />
          <window.FtiMindLogo.Wordmark size={13} />
        </div>
        <div style={{ flex: 1 }} />
        <span style={{ fontSize: 12, color: "var(--text-3)", display: "inline-flex", alignItems: "center", gap: 6 }}>
          {current && <Icon name={current.icon} size={13} />}
          {current?.label}
        </span>
      </div>

      {/* Slide-in drawer (overlay + panel) */}
      <div className="af-drawer-root" style={{
        position: "fixed", inset: 0, zIndex: 200,
        pointerEvents: open ? "auto" : "none",
        display: "none",
      }}>
        <div onClick={() => setOpen(false)} style={{
          position: "absolute", inset: 0,
          background: "rgba(0,0,0,0.5)",
          opacity: open ? 1 : 0,
          transition: "opacity 0.2s ease",
        }} />
        <aside style={{
          position: "absolute", top: 0, bottom: 0, left: 0,
          width: "min(280px, 82vw)",
          background: "var(--bg-1)",
          borderRight: "1px solid var(--line)",
          padding: "18px 14px",
          display: "flex", flexDirection: "column",
          transform: open ? "translateX(0)" : "translateX(-100%)",
          transition: "transform 0.24s cubic-bezier(0.32, 0.72, 0, 1)",
          boxShadow: open ? "0 0 40px rgba(0,0,0,0.3)" : "none",
        }}>
          <div style={{ display: "flex", alignItems: "center", gap: 8, marginBottom: 22 }}>
            <window.FtiMindLogo.Mark size={24} />
            <window.FtiMindLogo.Wordmark size={14} />
            <span style={{ fontSize: 9, color: "var(--text-3)", fontFamily: "var(--font-mono)" }}>v0.4</span>
            <div style={{ flex: 1 }} />
            <button onClick={() => setOpen(false)} aria-label="Cerrar" style={{
              width: 30, height: 30, borderRadius: "var(--r-2)",
              border: "1px solid var(--line)",
              background: "transparent", color: "var(--text-2)",
              display: "grid", placeItems: "center",
            }}>
              <Icon name="close" size={14} />
            </button>
          </div>

          <nav style={{ display: "flex", flexDirection: "column", gap: 2 }}>
            {NAV.map((n) => (
              <button key={n.id} onClick={() => goto(n.id)} style={{
                display: "flex", alignItems: "center", gap: 12,
                padding: "11px 12px",
                border: "none",
                borderRadius: "var(--r-2)",
                background: route === n.id ? "var(--bg-3)" : "transparent",
                color: route === n.id ? "var(--text)" : "var(--text-2)",
                fontSize: 14, fontWeight: 500, textAlign: "left",
              }}>
                <Icon name={n.icon} size={17} />
                {n.label}
              </button>
            ))}
          </nav>

          <div style={{ flex: 1 }} />

          <div style={{ display: "flex", alignItems: "center", gap: 10, padding: "10px 4px 0", borderTop: "1px solid var(--line-soft)" }}>
            <div style={{
              width: 28, height: 28, borderRadius: "50%",
              background: "var(--accent)", color: "var(--accent-fg)",
              display: "grid", placeItems: "center",
              fontWeight: 600, fontSize: 12,
            }}>D</div>
            <div style={{ minWidth: 0, flex: 1 }}>
              <div style={{ fontSize: 13, fontWeight: 500 }}>Daniel</div>
              <div style={{ fontSize: 10.5, color: "var(--text-3)" }}>self-hosted</div>
            </div>
          </div>
        </aside>
      </div>
    </>
  );
};

const TopBar = ({ title, subtitle, breadcrumb, actions, density, setDensity }) => {
  return (
    <header className="af-topbar" style={{
      display: "flex", alignItems: "flex-end", gap: 16,
      padding: "var(--sp-6) var(--sp-8) var(--sp-5)",
      borderBottom: "1px solid var(--line)",
    }}>
      <div style={{ flex: 1, minWidth: 0 }}>
        {breadcrumb && (
          <div className="eyebrow af-hide-mobile" style={{ marginBottom: 6 }}>{breadcrumb}</div>
        )}
        <h1 className="display" style={{
          margin: 0, fontSize: 32, lineHeight: 1.1, letterSpacing: "-0.025em",
          fontWeight: 400,
        }}>{title}</h1>
        {subtitle && (
          <div style={{ marginTop: 6, color: "var(--text-2)", fontSize: 13 }}>{subtitle}</div>
        )}
      </div>
      <div className="af-topbar-actions" style={{ display: "flex", alignItems: "center", gap: 10, paddingBottom: 6 }}>
        {/* Density toggle oculto — el dato `compact` queda como default fijo
         * en app.jsx. Si más adelante hace falta un toggle, vive en el panel
         * de Preferencias (Cmd/Ctrl+.) sin ensuciar la topbar. */}
        {actions}
      </div>
    </header>
  );
};

const EmptyState = ({ icon = "info", title, body, action }) => (
  <div style={{
    padding: 48, textAlign: "center", display: "grid", placeItems: "center", gap: 10,
    border: "1px dashed var(--line)", borderRadius: "var(--r-3)",
    color: "var(--text-3)",
  }}>
    <div style={{
      width: 44, height: 44, borderRadius: "50%",
      background: "var(--bg-2)", border: "1px solid var(--line)",
      display: "grid", placeItems: "center",
    }}>
      <Icon name={icon} size={20} color="var(--text-3)" />
    </div>
    <div style={{ fontSize: 14, fontWeight: 500, color: "var(--text)" }}>{title}</div>
    {body && <div style={{ fontSize: 12.5, maxWidth: 320, lineHeight: 1.5 }}>{body}</div>}
    {action}
  </div>
);

const Skel = ({ w = "100%", h = 14, r = 4 }) => (
  <div style={{
    width: w, height: h, borderRadius: r,
    background: "linear-gradient(90deg, var(--bg-2), var(--bg-3), var(--bg-2))",
    backgroundSize: "200% 100%",
    animation: "skel-pulse 1.4s ease-in-out infinite",
  }} />
);

Object.assign(window, { Sidebar, MobileNav, TopBar, EmptyState, Skel, NAV });
