/* 2.3 — Ecosistema, Networking & Articulación */

function Networking({ role }) {
  const [tab, setTab] = useState("red");
  return (
    <div className="page" data-screen-label="2.3 Networking">
      <div className="page-head">
        <div>
          <div className="meta">MÓDULO 2.3 · INTERACCIÓN ENTRE ACTORES</div>
          <h1>Ecosistema · Networking & Articulación</h1>
          <div className="sub">Visualización de la red de conexiones, directorio público, gestión de solicitudes y mensajería interna entre actores.</div>
        </div>
        <div className="flex gap-8">
          <button className="btn"><Icon name="download" size={13}/> Exportar grafo</button>
          <button className="btn btn-primary"><Icon name="plus" size={13}/> Nueva conexión</button>
        </div>
      </div>

      <div className="tabs">
        <div className={`tab ${tab === "red" ? "active" : ""}`} onClick={() => setTab("red")}>Vista de red</div>
        <div className={`tab ${tab === "directorio" ? "active" : ""}`} onClick={() => setTab("directorio")}>Directorio público</div>
        <div className={`tab ${tab === "conexiones" ? "active" : ""}`} onClick={() => setTab("conexiones")}>Conexiones <span className="badge">22</span></div>
        <div className={`tab ${tab === "solicitudes" ? "active" : ""}`} onClick={() => setTab("solicitudes")}>Solicitudes <span className="badge">14</span></div>
        <div className={`tab ${tab === "mensajes" ? "active" : ""}`} onClick={() => setTab("mensajes")}>Mensajería</div>
      </div>

      {tab === "red" && <VistaRed/>}
      {tab === "directorio" && <DirectorioPublico/>}
      {tab === "conexiones" && <ConexionesList/>}
      {tab === "solicitudes" && <Solicitudes/>}
      {tab === "mensajes" && <Mensajeria/>}
    </div>
  );
}

// ───── Vista de red (force-directed) ─────
function VistaRed() {
  const [filterTipo, setFilterTipo] = useState(new Set(window.TIPOS_ACTOR.map(t => t.id)));
  const [filterRegion, setFilterRegion] = useState("");
  const [tipoConex, setTipoConex] = useState("");
  const [selected, setSelected] = useState(null);
  const [selectedDepto, setSelectedDepto] = useState(null);
  const [viewMode, setViewMode] = useState("grafo"); // 'grafo' | 'mapa'
  const svgRef = useRef(null);

  const { nodes, links } = useMemo(() => {
    const filteredActors = window.ACTORES.filter(a => {
      if (!filterTipo.has(a.tipo)) return false;
      if (filterRegion) {
        const d = window.DEPARTAMENTOS.find(x => x.name === a.depto);
        if (!d || d.region !== filterRegion) return false;
      }
      return true;
    });
    const ids = new Set(filteredActors.map(a => a.id));
    const filteredConex = window.CONEXIONES.filter(c =>
      ids.has(c.from) && ids.has(c.to) && (!tipoConex || c.tipo === tipoConex)
    );
    return {
      nodes: filteredActors.map(a => ({ ...a, x: 400 + Math.random() * 200 - 100, y: 300 + Math.random() * 200 - 100, vx: 0, vy: 0 })),
      links: filteredConex.map(c => ({ ...c }))
    };
  }, [filterTipo, filterRegion, tipoConex]);

  // Force simulation
  const [positions, setPositions] = useState({});

  useEffect(() => {
    if (!nodes.length) return;
    const W = 760, H = 480;
    const cx = W / 2, cy = H / 2;
    // Initial cluster by tipo
    const sectorCenters = {};
    const tipoSet = [...new Set(nodes.map(n => n.tipo))];
    tipoSet.forEach((t, i) => {
      const angle = (i / tipoSet.length) * 2 * Math.PI;
      sectorCenters[t] = { x: cx + Math.cos(angle) * 180, y: cy + Math.sin(angle) * 180 };
    });
    const sim = nodes.map(n => ({
      id: n.id,
      x: sectorCenters[n.tipo].x + (Math.random() - 0.5) * 50,
      y: sectorCenters[n.tipo].y + (Math.random() - 0.5) * 50,
      vx: 0, vy: 0,
      tipo: n.tipo
    }));
    const linkMap = links.map(l => ({ from: sim.find(s => s.id === l.from), to: sim.find(s => s.id === l.to) })).filter(l => l.from && l.to);

    let frame = 0;
    const tick = () => {
      // Repulsion
      for (let i = 0; i < sim.length; i++) {
        for (let j = i + 1; j < sim.length; j++) {
          const a = sim[i], b = sim[j];
          const dx = b.x - a.x, dy = b.y - a.y;
          const d2 = dx * dx + dy * dy + 0.1;
          const d = Math.sqrt(d2);
          const f = 300 / d2;
          a.vx -= (dx / d) * f;
          a.vy -= (dy / d) * f;
          b.vx += (dx / d) * f;
          b.vy += (dy / d) * f;
        }
      }
      // Link attraction
      linkMap.forEach(l => {
        const dx = l.to.x - l.from.x, dy = l.to.y - l.from.y;
        const d = Math.sqrt(dx * dx + dy * dy) + 0.1;
        const f = (d - 60) * 0.02;
        l.from.vx += (dx / d) * f;
        l.from.vy += (dy / d) * f;
        l.to.vx -= (dx / d) * f;
        l.to.vy -= (dy / d) * f;
      });
      // Center pull
      sim.forEach(s => {
        s.vx += (cx - s.x) * 0.005;
        s.vy += (cy - s.y) * 0.005;
        // Cluster pull
        const center = sectorCenters[s.tipo];
        s.vx += (center.x - s.x) * 0.01;
        s.vy += (center.y - s.y) * 0.01;
        // velocity damping & apply
        s.vx *= 0.85;
        s.vy *= 0.85;
        s.x += s.vx;
        s.y += s.vy;
        // Bounds
        s.x = Math.max(30, Math.min(W - 30, s.x));
        s.y = Math.max(30, Math.min(H - 30, s.y));
      });

      setPositions(Object.fromEntries(sim.map(s => [s.id, { x: s.x, y: s.y }])));

      frame++;
      if (frame < 120) requestAnimationFrame(tick);
    };
    requestAnimationFrame(tick);
  }, [nodes, links]);

  const toggleTipo = (id) => {
    const s = new Set(filterTipo);
    if (s.has(id)) s.delete(id); else s.add(id);
    setFilterTipo(s);
  };

  const connectionTypes = ["mentoria", "alianza", "lead", "inversion"];
  const connColors = { mentoria: "#7c5a1f", alianza: "#1b7a4d", lead: "#c97a16", inversion: "#a83a5b" };

  return (
    <div style={{ display: "grid", gridTemplateColumns: "260px 1fr 280px", gap: 16, height: "calc(100vh - 240px)" }}>
      {/* Left filters */}
      <div className="card" style={{ overflow: "auto" }}>
        <div className="card-head"><h3>Filtros de red</h3></div>
        <div className="card-body">
          <div style={{ fontSize: 11, textTransform: "uppercase", letterSpacing: "0.06em", color: "var(--c-ink-5)", fontWeight: 600, marginBottom: 6 }}>Tipo de actor</div>
          <div style={{ display: "flex", flexDirection: "column", gap: 4, marginBottom: 14 }}>
            {window.TIPOS_ACTOR.slice(0, 11).map(t => (
              <label key={t.id} style={{ display: "flex", alignItems: "center", gap: 8, fontSize: 11.5, cursor: "pointer" }}>
                <input type="checkbox" checked={filterTipo.has(t.id)} onChange={() => toggleTipo(t.id)}/>
                <span style={{ width: 10, height: 10, background: t.color, borderRadius: 2 }}/>
                <span>{t.label}</span>
              </label>
            ))}
          </div>

          <div style={{ fontSize: 11, textTransform: "uppercase", letterSpacing: "0.06em", color: "var(--c-ink-5)", fontWeight: 600, marginBottom: 6 }}>Región</div>
          <select className="select" value={filterRegion} onChange={e => setFilterRegion(e.target.value)} style={{ marginBottom: 14 }}>
            <option value="">Todas</option>
            <option value="Andina">Andina</option>
            <option value="Caribe">Caribe</option>
            <option value="Pacífica">Pacífica</option>
            <option value="Orinoquía">Orinoquía</option>
            <option value="Amazonía">Amazonía</option>
          </select>

          <div style={{ fontSize: 11, textTransform: "uppercase", letterSpacing: "0.06em", color: "var(--c-ink-5)", fontWeight: 600, marginBottom: 6 }}>Tipo de conexión</div>
          <select className="select" value={tipoConex} onChange={e => setTipoConex(e.target.value)}>
            <option value="">Todas</option>
            <option value="mentoria">Mentoría</option>
            <option value="alianza">Alianza</option>
            <option value="lead">Lead comercial</option>
            <option value="inversion">Inversión</option>
          </select>

          <div style={{ marginTop: 18, paddingTop: 14, borderTop: "1px solid var(--c-line)" }}>
            <div style={{ fontSize: 11, textTransform: "uppercase", letterSpacing: "0.06em", color: "var(--c-ink-5)", fontWeight: 600, marginBottom: 8 }}>Métricas de la vista</div>
            <div style={{ display: "flex", justifyContent: "space-between", fontSize: 11.5, padding: "4px 0" }}><span className="muted">Nodos</span><span className="mono">{nodes.length}</span></div>
            <div style={{ display: "flex", justifyContent: "space-between", fontSize: 11.5, padding: "4px 0" }}><span className="muted">Aristas</span><span className="mono">{links.length}</span></div>
            <div style={{ display: "flex", justifyContent: "space-between", fontSize: 11.5, padding: "4px 0" }}><span className="muted">Densidad</span><span className="mono">{(links.length / (nodes.length * (nodes.length - 1) / 2 || 1)).toFixed(3)}</span></div>
            <div style={{ display: "flex", justifyContent: "space-between", fontSize: 11.5, padding: "4px 0" }}><span className="muted">Grado prom.</span><span className="mono">{nodes.length ? (2 * links.length / nodes.length).toFixed(1) : 0}</span></div>
          </div>
        </div>
      </div>

      {/* Graph / Map */}
      <div className="card" style={{ overflow: "hidden", display: "flex", flexDirection: "column" }}>
        <div className="card-head">
          <h3>{viewMode === "grafo" ? "Grafo del ecosistema · clústeres por tipo de actor" : "Mapa geográfico · actores y conexiones por departamento"}</h3>
          <div className="flex gap-12 items-center">
            {viewMode === "grafo" && (
              <div className="flex gap-8 text-xs">
                {connectionTypes.map(c => (
                  <span key={c} style={{ display: "inline-flex", alignItems: "center", gap: 4 }}>
                    <span style={{ width: 12, height: 2, background: connColors[c] }}/>
                    <span style={{ textTransform: "capitalize" }}>{c}</span>
                  </span>
                ))}
              </div>
            )}
            {viewMode === "mapa" && (
              <div className="flex gap-8 text-xs">
                {Object.entries(window.REGION_COLORS).map(([r, c]) => (
                  <span key={r} style={{ display: "inline-flex", alignItems: "center", gap: 4 }}>
                    <span style={{ width: 8, height: 8, background: c, borderRadius: 2 }}/>
                    <span>{r}</span>
                  </span>
                ))}
              </div>
            )}
            {/* View toggle */}
            <div style={{ display: "inline-flex", border: "1px solid var(--c-line)", borderRadius: 6, overflow: "hidden" }}>
              <button
                onClick={() => setViewMode("grafo")}
                className="btn btn-sm"
                style={{
                  border: "none", borderRadius: 0,
                  background: viewMode === "grafo" ? "var(--c-primary)" : "#fff",
                  color: viewMode === "grafo" ? "#fff" : "var(--c-ink-3)"
                }}>
                <Icon name="network" size={11}/> Grafo
              </button>
              <button
                onClick={() => setViewMode("mapa")}
                className="btn btn-sm"
                style={{
                  border: "none", borderRadius: 0, borderLeft: "1px solid var(--c-line)",
                  background: viewMode === "mapa" ? "var(--c-primary)" : "#fff",
                  color: viewMode === "mapa" ? "#fff" : "var(--c-ink-3)"
                }}>
                <Icon name="map" size={11}/> Mapa Colombia
              </button>
            </div>
          </div>
        </div>
        <div style={{ flex: 1, background: "linear-gradient(180deg, #fafbfc 0%, #f7f8fa 100%)", position: "relative", overflow: "hidden" }}>
          {viewMode === "grafo" && (
            <svg ref={svgRef} viewBox="0 0 760 480" width="100%" height="100%" preserveAspectRatio="xMidYMid meet">
            <defs>
              <pattern id="grid" width="40" height="40" patternUnits="userSpaceOnUse">
                <path d="M 40 0 L 0 0 0 40" fill="none" stroke="#e2e5ea" strokeWidth="0.5"/>
              </pattern>
            </defs>
            <rect width="760" height="480" fill="url(#grid)"/>
            {/* Links */}
            {links.map((l, i) => {
              const from = positions[l.from];
              const to = positions[l.to];
              if (!from || !to) return null;
              return (
                <line key={i} x1={from.x} y1={from.y} x2={to.x} y2={to.y}
                  stroke={connColors[l.tipo] || "#888"}
                  strokeOpacity={l.estado === "activa" ? 0.55 : 0.25}
                  strokeWidth={l.estado === "cerrada" ? 2 : 1.2}
                  strokeDasharray={l.estado === "negociacion" ? "3 3" : ""}/>
              );
            })}
            {/* Nodes */}
            {nodes.map(n => {
              const p = positions[n.id] || { x: n.x, y: n.y };
              const isSel = selected && selected.id === n.id;
              const deg = links.filter(l => l.from === n.id || l.to === n.id).length;
              const r = 6 + Math.min(deg * 1.5, 8);
              return (
                <g key={n.id} transform={`translate(${p.x}, ${p.y})`} style={{ cursor: "pointer" }} onClick={() => setSelected(n)}>
                  {isSel && <circle r={r + 6} fill="none" stroke="var(--c-primary)" strokeWidth="2" strokeDasharray="3 2"/>}
                  <circle r={r} fill={window.colorFor(n.tipo)} stroke="#fff" strokeWidth="1.5"/>
                  {(isSel || deg >= 3) && (
                    <text y={r + 12} textAnchor="middle" style={{ fontSize: 9.5, fontFamily: "var(--font-sans)", fontWeight: 500, fill: "var(--c-ink-2)", pointerEvents: "none" }}>
                      {n.nombre.length > 22 ? n.nombre.substring(0, 22) + "…" : n.nombre}
                    </text>
                  )}
                </g>
              );
            })}
          </svg>
          )}
          {viewMode === "mapa" && (
            <window.ColombiaMap
              actores={nodes}
              conexiones={links}
              onSelectDepto={(depto, list) => { setSelectedDepto(depto); setSelected(null); }}
              selectedDepto={selectedDepto}/>
          )}
          <div style={{ position: "absolute", bottom: 10, left: 10, fontSize: 10, color: "var(--c-ink-5)", background: "rgba(255,255,255,0.85)", padding: "4px 8px", borderRadius: 4, fontFamily: "var(--font-mono)" }}>
            {viewMode === "grafo"
              ? "Simulación force-directed · Clústeres por tipo de actor · Tamaño = grado de conexión"
              : "Proyección equirectangular · Tamaño del nodo = densidad de actores · Arcos = conexiones inter-departamentales"}
          </div>
        </div>
      </div>

      {/* Right: detail */}
      <div className="card" style={{ overflow: "auto" }}>
        <div className="card-head"><h3>Detalle</h3></div>
        <div className="card-body">
          {!selected && !selectedDepto && (
            <div style={{ textAlign: "center", padding: "30px 10px", color: "var(--c-ink-5)" }}>
              <Icon name={viewMode === "mapa" ? "map" : "network"} size={32}/>
              <div style={{ fontSize: 12, marginTop: 8 }}>
                {viewMode === "mapa"
                  ? "Selecciona un departamento en el mapa para ver sus actores."
                  : "Selecciona un nodo para ver sus conexiones e indicadores."}
              </div>
            </div>
          )}
          {selectedDepto && viewMode === "mapa" && (() => {
            const list = nodes.filter(n => n.depto === selectedDepto);
            const dept = window.DEPARTAMENTOS.find(d => d.name === selectedDepto);
            const innerConx = links.filter(l => {
              const fa = window.ACTORES.find(a => a.id === l.from);
              const ta = window.ACTORES.find(a => a.id === l.to);
              return (fa && fa.depto === selectedDepto) || (ta && ta.depto === selectedDepto);
            });
            return (
              <>
                <div style={{ marginBottom: 12 }}>
                  <div style={{ fontFamily: "var(--font-serif)", fontSize: 17, fontWeight: 600 }}>{selectedDepto}</div>
                  <div style={{ fontSize: 11, color: "var(--c-ink-4)" }}>Región {dept ? dept.region : ""} · DANE {dept ? dept.code : ""}</div>
                </div>
                <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 6, marginBottom: 14 }}>
                  <Stat label="Actores (total)" v={(dept ? dept.actores : list.length).toLocaleString()}/>
                  <Stat label="En esta vista" v={list.length}/>
                  <Stat label="Conexiones" v={innerConx.length}/>
                  <Stat label="Región" v={dept ? dept.region : "—"}/>
                </div>
                <div style={{ fontSize: 10, textTransform: "uppercase", letterSpacing: "0.06em", color: "var(--c-ink-5)", fontWeight: 600, marginBottom: 6 }}>Actores en {selectedDepto}</div>
                {list.map(a => (
                  <div key={a.id} onClick={() => setSelected(a)}
                    style={{ display: "flex", alignItems: "center", gap: 8, padding: "7px 0", borderBottom: "1px solid var(--c-line-2)", cursor: "pointer" }}>
                    <Swatch tipo={a.tipo} size={26}/>
                    <div style={{ flex: 1, minWidth: 0 }}>
                      <div style={{ fontSize: 12, fontWeight: 500, whiteSpace: "nowrap", overflow: "hidden", textOverflow: "ellipsis" }}>{a.nombre}</div>
                      <div style={{ fontSize: 10.5, color: "var(--c-ink-4)" }}>{window.labelFor(a.tipo)}</div>
                    </div>
                    <span className="mono text-xs muted">{a.conexiones}</span>
                  </div>
                ))}
                {list.length === 0 && (
                  <div style={{ fontSize: 11, color: "var(--c-ink-5)", padding: "10px 0" }}>
                    Sin actores que coincidan con los filtros actuales.
                  </div>
                )}
              </>
            );
          })()}
          {selected && (
            <>
              <div style={{ display: "flex", alignItems: "center", gap: 10, marginBottom: 12 }}>
                <Swatch tipo={selected.tipo} size={36}/>
                <div>
                  <div style={{ fontWeight: 600, fontSize: 13 }}>{selected.nombre}</div>
                  <div style={{ fontSize: 11, color: "var(--c-ink-4)" }}>{window.labelFor(selected.tipo)} · {selected.depto}</div>
                </div>
              </div>
              <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 6, marginBottom: 12 }}>
                <Stat label="Conexiones" v={selected.conexiones}/>
                <Stat label="Madurez" v={`${selected.madurez}/5`}/>
                <Stat label="Empleados" v={selected.empleados}/>
                <Stat label="Sector" v={selected.sector}/>
              </div>
              <div style={{ fontSize: 10, textTransform: "uppercase", letterSpacing: "0.06em", color: "var(--c-ink-5)", fontWeight: 600, marginBottom: 6 }}>Conexiones en esta vista</div>
              {links.filter(l => l.from === selected.id || l.to === selected.id).map((l, i) => {
                const otherId = l.from === selected.id ? l.to : l.from;
                const other = window.ACTORES.find(a => a.id === otherId);
                if (!other) return null;
                return (
                  <div key={i} style={{ display: "flex", alignItems: "center", gap: 6, padding: "6px 0", borderBottom: "1px solid var(--c-line-2)", fontSize: 11.5 }}>
                    <span style={{ width: 8, height: 8, background: connColors[l.tipo], borderRadius: 2 }}/>
                    <span style={{ flex: 1 }}>{other.nombre}</span>
                    <span className="chip" style={{ fontSize: 9.5 }}>{l.tipo}</span>
                  </div>
                );
              })}
              <button className="btn btn-primary btn-sm" style={{ width: "100%", marginTop: 12, justifyContent: "center" }}>
                <Icon name="msg" size={11}/> Contactar
              </button>
            </>
          )}
        </div>
      </div>
    </div>
  );
}

function Stat({ label, v }) {
  return (
    <div style={{ padding: 8, background: "var(--c-bg)", borderRadius: 4 }}>
      <div style={{ fontSize: 9.5, textTransform: "uppercase", letterSpacing: "0.06em", color: "var(--c-ink-5)" }}>{label}</div>
      <div style={{ fontFamily: "var(--font-mono)", fontSize: 13, fontWeight: 600 }}>{v}</div>
    </div>
  );
}

// ───── Directorio público ─────
function DirectorioPublico() {
  const [q, setQ] = useState("");
  const filtered = window.ACTORES.filter(a => !q || a.nombre.toLowerCase().includes(q.toLowerCase()) || a.oferta.toLowerCase().includes(q.toLowerCase()));
  return (
    <>
      <div className="filterbar" style={{ marginBottom: 12 }}>
        <div className="field" style={{ flex: 1 }}>
          <label>Búsqueda full-text</label>
          <input placeholder="Buscar por nombre, oferta, necesidad, sector…" value={q} onChange={e => setQ(e.target.value)}/>
        </div>
        <span className="count">{filtered.length} perfiles públicos</span>
      </div>
      <div className="grid-3">
        {filtered.slice(0, 9).map(a => (
          <div key={a.id} className="card">
            <div style={{ padding: 16, display: "flex", flexDirection: "column", gap: 10 }}>
              <div style={{ display: "flex", alignItems: "center", gap: 10 }}>
                <Swatch tipo={a.tipo} size={36}/>
                <div>
                  <div style={{ fontWeight: 600, fontSize: 13.5 }}>{a.nombre}</div>
                  <div style={{ fontSize: 11, color: "var(--c-ink-4)" }}>{window.labelFor(a.tipo)} · {a.depto}</div>
                </div>
              </div>
              <div style={{ fontSize: 11.5, color: "var(--c-ink-3)", lineHeight: 1.4, minHeight: 50 }}>{a.oferta}</div>
              <div style={{ display: "flex", gap: 4, flexWrap: "wrap" }}>
                {a.arenas.map(x => <span key={x} className="chip info">{x}</span>)}
              </div>
              <div style={{ display: "flex", gap: 10, fontSize: 11, color: "var(--c-ink-4)", paddingTop: 8, borderTop: "1px solid var(--c-line-2)" }}>
                <span><b style={{ color: "var(--c-ink-2)" }}>{a.conexiones}</b> conexiones</span>
                <span>·</span>
                <span>Madurez <b style={{ color: "var(--c-ink-2)" }}>{a.madurez}/5</b></span>
                <span style={{ marginLeft: "auto" }}>
                  <button className="btn btn-sm btn-primary"><Icon name="network" size={10}/> Conectar</button>
                </span>
              </div>
            </div>
          </div>
        ))}
      </div>
    </>
  );
}

// ───── Conexiones list ─────
function ConexionesList() {
  const conexionesEnriquecidas = window.CONEXIONES.map(c => {
    const from = window.ACTORES.find(a => a.id === c.from);
    const to = window.ACTORES.find(a => a.id === c.to);
    return { ...c, from, to };
  }).filter(c => c.from && c.to);

  const counts = {
    mentoria: conexionesEnriquecidas.filter(c => c.tipo === "mentoria").length,
    alianza: conexionesEnriquecidas.filter(c => c.tipo === "alianza").length,
    lead: conexionesEnriquecidas.filter(c => c.tipo === "lead").length,
    inversion: conexionesEnriquecidas.filter(c => c.tipo === "inversion").length,
  };

  return (
    <>
      <div className="grid-kpis">
        <KpiTile label="Mentorías" value={counts.mentoria} sub="Activas · 2,847 h acumuladas"/>
        <KpiTile label="Alianzas" value={counts.alianza} sub="89 formalizadas YTD" delta="+14"/>
        <KpiTile label="Leads comerciales" value={counts.lead} sub="Tasa de conversión 24%"/>
        <KpiTile label="Inversión" value={counts.inversion} accent sub="$14.8M USD gestionados"/>
      </div>
      <div className="card">
        <table className="data">
          <thead><tr><th>Fecha</th><th>De</th><th>A</th><th>Tipo</th><th>Estado</th><th>Resultado</th><th></th></tr></thead>
          <tbody>
            {conexionesEnriquecidas.map((c, i) => (
              <tr key={i}>
                <td className="mono">{c.fecha}</td>
                <td><span className="cell-strong">{c.from.nombre}</span><div className="cell-sub">{window.labelFor(c.from.tipo)}</div></td>
                <td><span className="cell-strong">{c.to.nombre}</span><div className="cell-sub">{window.labelFor(c.to.tipo)}</div></td>
                <td><span className="chip" style={{ textTransform: "capitalize" }}>{c.tipo}</span></td>
                <td>
                  <span className={`chip ${c.estado === "activa" ? "success" : c.estado === "negociacion" ? "warn" : "info"}`} style={{ textTransform: "capitalize" }}>
                    <span className="dot"/>{c.estado}
                  </span>
                </td>
                <td className="text-xs muted">{c.tipo === "inversion" ? "Ronda · seguimiento" : c.tipo === "mentoria" ? "60min · evaluado 4.8/5" : "Pendiente cierre"}</td>
                <td><button className="btn btn-sm btn-ghost"><Icon name="eye" size={11}/></button></td>
              </tr>
            ))}
          </tbody>
        </table>
      </div>
    </>
  );
}

// ───── Solicitudes ─────
function Solicitudes() {
  const t = useToast();
  const [items, setItems] = useState([
    { id: 1, de: "Pacífico Fintech", deTipo: "startup_escalamiento", tipo: "mentoria", mensaje: "Buscamos mentoría regulatoria fintech para Serie B." },
    { id: 2, de: "Tunja Agritech", deTipo: "mipyme", tipo: "alianza", mensaje: "Interesados en pilotear nuestros drones con cooperativa cafetera del Quindío." },
    { id: 3, de: "Capital Andino Ventures", deTipo: "inversionista", tipo: "inversion", mensaje: "Quisiéramos profundizar sobre tracción últimos 6 meses." },
    { id: 4, de: "Universidad del Bosque Andino", deTipo: "academica", tipo: "alianza", mensaje: "Convenio para semestre de práctica de 4 estudiantes de ingeniería." },
    { id: 5, de: "Bioandes Salud Digital", deTipo: "startup_temprana", tipo: "alianza", mensaje: "Compartir aprendizajes en cumplimiento HIPAA / Habeas Data." },
  ]);

  const act = (id, action) => {
    setItems(items.filter(x => x.id !== id));
    t.push(action === "accept" ? "Solicitud aceptada · Conexión registrada" : "Solicitud rechazada", "success");
  };

  return (
    <div className="card">
      <div className="card-head"><h3>Solicitudes entrantes · pendientes de respuesta</h3><span className="chip warn">{items.length} pendientes</span></div>
      <div className="card-body" style={{ padding: 0 }}>
        {items.map(it => (
          <div key={it.id} style={{ display: "flex", gap: 14, padding: 16, borderBottom: "1px solid var(--c-line-2)", alignItems: "flex-start" }}>
            <Swatch tipo={it.deTipo} size={40}/>
            <div style={{ flex: 1 }}>
              <div style={{ display: "flex", alignItems: "center", gap: 6, marginBottom: 2 }}>
                <span style={{ fontWeight: 600, fontSize: 13 }}>{it.de}</span>
                <span className="chip" style={{ textTransform: "capitalize" }}>{it.tipo}</span>
              </div>
              <div style={{ fontSize: 12, color: "var(--c-ink-3)", lineHeight: 1.45 }}>"{it.mensaje}"</div>
            </div>
            <div style={{ display: "flex", gap: 6 }}>
              <button className="btn btn-sm" onClick={() => act(it.id, "reject")}><Icon name="x" size={11}/> Rechazar</button>
              <button className="btn btn-sm btn-primary" onClick={() => act(it.id, "accept")}><Icon name="check" size={11}/> Aceptar</button>
            </div>
          </div>
        ))}
        {items.length === 0 && <div style={{ padding: 40, textAlign: "center", color: "var(--c-ink-5)" }}>Sin solicitudes pendientes.</div>}
      </div>
    </div>
  );
}

// ───── Mensajería ─────
function Mensajeria() {
  const [active, setActive] = useState("a11");
  const [draft, setDraft] = useState("");
  const t = useToast();
  const conversations = [
    { id: "a11", with: "Capital Andino Ventures", tipo: "inversionista", last: "Confirmamos reunión jueves 4pm", unread: 2, time: "14:21" },
    { id: "a15", with: "Alma Mentoring", tipo: "mentor", last: "Te dejé feedback en el deck", unread: 0, time: "Ayer" },
    { id: "a14", with: "Grupo Energía Norte", tipo: "corporativo", last: "Equipo legal revisará NDA", unread: 1, time: "Ayer" },
    { id: "a09", with: "Cámara de Comercio Quindío", tipo: "camara", last: "Cupo confirmado para Demo Day", unread: 0, time: "23-may" },
    { id: "a10", with: "U. del Bosque Andino", tipo: "academica", last: "Adjunto convenio marco", unread: 0, time: "22-may" },
  ];
  const messages = [
    { from: "Capital Andino Ventures", time: "14:21", text: "Hola Juliana, vimos las métricas del Q1 y queríamos profundizar." },
    { from: "Yo", time: "14:24", text: "Claro, podemos agendar esta semana." },
    { from: "Capital Andino Ventures", time: "14:25", text: "¿Jueves 4pm te funciona? Vendría todo el equipo de inversión." },
    { from: "Yo", time: "14:26", text: "Perfecto. ¿En oficinas de ustedes?" },
    { from: "Capital Andino Ventures", time: "14:28", text: "Sí, sala principal. ¿Necesitas algo específico para la presentación?" },
  ];

  return (
    <div className="card" style={{ overflow: "hidden", height: "calc(100vh - 240px)" }}>
      <div style={{ display: "grid", gridTemplateColumns: "300px 1fr", height: "100%" }}>
        <div style={{ borderRight: "1px solid var(--c-line)", overflow: "auto" }}>
          <div style={{ padding: 12, borderBottom: "1px solid var(--c-line)" }}>
            <input className="input" placeholder="Buscar conversación…"/>
          </div>
          {conversations.map(c => (
            <div key={c.id}
              onClick={() => setActive(c.id)}
              style={{
                padding: 12, borderBottom: "1px solid var(--c-line-2)", cursor: "pointer",
                background: active === c.id ? "var(--c-primary-50)" : "transparent",
                display: "flex", gap: 10, alignItems: "center"
              }}>
              <Swatch tipo={c.tipo} size={36}/>
              <div style={{ flex: 1, minWidth: 0 }}>
                <div style={{ display: "flex", justifyContent: "space-between" }}>
                  <span style={{ fontWeight: 600, fontSize: 12.5 }}>{c.with}</span>
                  <span style={{ fontSize: 10, color: "var(--c-ink-5)" }}>{c.time}</span>
                </div>
                <div style={{ fontSize: 11.5, color: "var(--c-ink-4)", whiteSpace: "nowrap", overflow: "hidden", textOverflow: "ellipsis" }}>{c.last}</div>
              </div>
              {c.unread > 0 && <span style={{ width: 18, height: 18, borderRadius: "50%", background: "var(--c-primary)", color: "#fff", fontSize: 10, display: "flex", alignItems: "center", justifyContent: "center", fontWeight: 600 }}>{c.unread}</span>}
            </div>
          ))}
        </div>
        <div style={{ display: "flex", flexDirection: "column" }}>
          <div style={{ padding: "12px 16px", borderBottom: "1px solid var(--c-line)", display: "flex", justifyContent: "space-between", alignItems: "center" }}>
            <div>
              <div style={{ fontWeight: 600, fontSize: 13 }}>Capital Andino Ventures</div>
              <div style={{ fontSize: 11, color: "var(--c-ink-4)" }}>Inversionista · activo hoy</div>
            </div>
            <div className="flex gap-8">
              <button className="btn btn-sm"><Icon name="calendar" size={11}/> Agendar</button>
              <button className="btn btn-sm"><Icon name="eye" size={11}/> Ver perfil</button>
            </div>
          </div>
          <div style={{ flex: 1, overflowY: "auto", padding: 20, background: "var(--c-bg)" }}>
            {messages.map((m, i) => (
              <div key={i} style={{ display: "flex", justifyContent: m.from === "Yo" ? "flex-end" : "flex-start", marginBottom: 10 }}>
                <div style={{
                  maxWidth: "70%",
                  background: m.from === "Yo" ? "var(--c-primary)" : "#fff",
                  color: m.from === "Yo" ? "#fff" : "var(--c-ink)",
                  padding: "8px 12px",
                  borderRadius: 8,
                  fontSize: 12.5,
                  lineHeight: 1.4,
                  border: m.from === "Yo" ? "none" : "1px solid var(--c-line)"
                }}>
                  {m.text}
                  <div style={{ fontSize: 10, opacity: 0.6, marginTop: 3, textAlign: "right" }}>{m.time}</div>
                </div>
              </div>
            ))}
          </div>
          <div style={{ padding: 12, borderTop: "1px solid var(--c-line)", display: "flex", gap: 8 }}>
            <input className="input" value={draft} onChange={e => setDraft(e.target.value)} placeholder="Escribe un mensaje…" style={{ flex: 1 }} onKeyDown={e => { if (e.key === "Enter" && draft) { t.push("Mensaje enviado", "success"); setDraft(""); } }}/>
            <button className="btn btn-primary" onClick={() => { if (draft) { t.push("Mensaje enviado", "success"); setDraft(""); } }}>Enviar</button>
          </div>
        </div>
      </div>
    </div>
  );
}

window.Networking = Networking;
