// Vista de Relaciones global — grafo interactivo + tabla
const { useState: useStateRel, useMemo: useMemoRel, useEffect: useEffectRel, useRef: useRefRel } = React;

// Construye un grafo completo de todos los CIs y sus relaciones
function buildGlobalGraph() {
  const D = window.CMDB_DATA;
  const nodes = [];
  const addNode = (id, kind, label, sub) => nodes.push({ id, kind, label, sub });
  D.empleados.forEach(e => addNode(e.id, 'USR', e.nombre, e.area));
  D.equipos.forEach(e => addNode(e.id, 'EQP', e.modelo, e.serie));
  D.servidores.forEach(s => addNode(s.id, 'SRV', s.nombre, s.tipo));
  D.licencias.forEach(l => addNode(l.id, 'LIC', l.producto, l.tipo));
  D.correos.forEach(m => addNode(m.id, 'MBX', m.direccion, m.tipo));
  D.proveedores.forEach(p => addNode(p.id, 'PRV', p.nombre, p.tipo));
  D.lineas.forEach(t => addNode(t.id, 'TEL', t.numero, t.compania));
  D.infraestructura.forEach(i => addNode(i.id, 'INF', i.modelo, i.tipo));

  const edges = [];
  const addEdge = (a, b, tipo) => edges.push({ a, b, tipo });

  D.equipos.forEach(e => {
    if (e.asignadoA) addEdge(e.id, e.asignadoA, 'asignación');
    if (e.proveedor) addEdge(e.id, e.proveedor, 'provisión');
  });
  D.servidores.forEach(s => {
    if (s.proveedor) addEdge(s.id, s.proveedor, 'provisión');
  });
  D.licencias.forEach(l => {
    if (l.proveedor) addEdge(l.id, l.proveedor, 'provisión');
  });
  D.correos.forEach(m => {
    if (m.asociado) addEdge(m.id, m.asociado, 'buzón');
  });
  D.lineas.forEach(t => {
    if (t.asignadoA) addEdge(t.id, t.asignadoA, 'línea telefónica');
  });
  D.infraestructura.forEach(i => {
    if (i.proveedor) addEdge(i.id, i.proveedor, 'provisión');
  });
  D.licenciaAsignaciones.forEach(la => {
    la.usuarios.forEach(u => addEdge(la.lic, u, 'licenciamiento'));
  });

  return { nodes, edges };
}

const EDGE_KINDS = {
  'asignación':    { label: 'Asignación de equipo',  color: 'oklch(50% 0.13 200)' },
  'provisión':     { label: 'Provisión',              color: 'oklch(55% 0.10 25)'  },
  'buzón':         { label: 'Buzón de correo',        color: 'oklch(58% 0.13 155)' },
  'licenciamiento':{ label: 'Licenciamiento',         color: 'oklch(60% 0.13 75)'  },
  'línea telefónica': { label: 'Línea telefónica',    color: 'oklch(60% 0.10 320)' },
};

// Layout en sectores: cada tipo ocupa una zona del lienzo
const SECTOR_LAYOUT = {
  // [angleDeg, radius% from center, gridCols, dot spacing]
  USR: { cx: 50, cy: 50,  cols: 6, gap: 5.2, gapY: 6 },
  EQP: { cx: 80, cy: 25,  cols: 5, gap: 4.5, gapY: 5 },
  SRV: { cx: 78, cy: 78,  cols: 4, gap: 4.5, gapY: 5 },
  LIC: { cx: 18, cy: 22,  cols: 4, gap: 5,   gapY: 5 },
  MBX: { cx: 16, cy: 78,  cols: 3, gap: 5,   gapY: 5 },
  PRV: { cx: 50, cy: 12,  cols: 8, gap: 5,   gapY: 5 },
  TEL: { cx: 50, cy: 88,  cols: 8, gap: 4,   gapY: 4 },
  INF: { cx: 85, cy: 50,  cols: 4, gap: 5,   gapY: 5 },
};

function layoutNodes(nodes) {
  // Group by kind
  const byKind = {};
  nodes.forEach(n => {
    byKind[n.kind] = byKind[n.kind] || [];
    byKind[n.kind].push(n);
  });
  const positioned = [];
  Object.entries(byKind).forEach(([kind, list]) => {
    const L = SECTOR_LAYOUT[kind];
    if (!L) return;
    const cols = L.cols;
    const rows = Math.ceil(list.length / cols);
    // Center the grid on (L.cx, L.cy)
    const totalW = (cols - 1) * L.gap;
    const totalH = (rows - 1) * L.gapY;
    list.forEach((n, i) => {
      const r = Math.floor(i / cols);
      const c = i % cols;
      const x = L.cx - totalW / 2 + c * L.gap;
      const y = L.cy - totalH / 2 + r * L.gapY;
      positioned.push({ ...n, x, y });
    });
  });
  return positioned;
}

// ===== Vista principal =====
function RelationsView({ onOpenCI }) {
  const D = window.CMDB_DATA;
  const graph = useMemoRel(buildGlobalGraph, []);
  const positioned = useMemoRel(() => layoutNodes(graph.nodes), [graph]);
  const nodeById = useMemoRel(() => {
    const m = {};
    positioned.forEach(n => m[n.id] = n);
    return m;
  }, [positioned]);

  const [activeTypes, setActiveTypes] = useStateRel(new Set(['USR','EQP','SRV','LIC','MBX','PRV','TEL','INF']));
  const [activeEdgeKinds, setActiveEdgeKinds] = useStateRel(new Set(Object.keys(EDGE_KINDS)));
  const [selected, setSelected] = usePersist('rel:sel', null);
  const [hover, setHover] = useStateRel(null);
  const [empFocus, setEmpFocus] = usePersist('rel:emp', null);
  const [empDegree, setEmpDegree] = usePersist('rel:deg', 2); // 1 = directos, 2 = +proveedores/áreas

  const toggleSet = (set, val) => {
    const s = new Set(set);
    if (s.has(val)) s.delete(val); else s.add(val);
    return s;
  };

  // ===== Subgrafo de un empleado seleccionado =====
  const empSubgraph = useMemoRel(() => {
    if (!empFocus) return null;
    const ids = new Set([empFocus]);
    const edges = [];
    // 1er grado: equipos, buzones, licencias del empleado
    graph.edges.forEach(e => {
      if (e.a === empFocus || e.b === empFocus) {
        ids.add(e.a); ids.add(e.b);
        edges.push(e);
      }
    });
    // 2do grado: proveedores de esos activos (sin re-explorar a empleados)
    if (empDegree >= 2) {
      const firstDegree = Array.from(ids).filter(id => id !== empFocus);
      graph.edges.forEach(e => {
        if (e.tipo !== 'provisión') return;
        if (firstDegree.includes(e.a) || firstDegree.includes(e.b)) {
          ids.add(e.a); ids.add(e.b);
          edges.push(e);
        }
      });
    }
    return { ids, edges: edges };
  }, [empFocus, empDegree, graph]);

  // Compute neighbor set for highlight
  const focusId = hover || selected;
  const neighborhood = useMemoRel(() => {
    if (!focusId) return null;
    const ids = new Set([focusId]);
    graph.edges.forEach(e => {
      if (e.a === focusId) ids.add(e.b);
      if (e.b === focusId) ids.add(e.a);
    });
    return ids;
  }, [focusId, graph]);

  // Filtered edges and nodes
  const visibleEdges = useMemoRel(() => graph.edges.filter(e => {
    if (!activeEdgeKinds.has(e.tipo)) return false;
    const na = nodeById[e.a], nb = nodeById[e.b];
    if (!na || !nb) return false;
    if (!activeTypes.has(na.kind) || !activeTypes.has(nb.kind)) return false;
    if (empSubgraph) {
      // sólo aristas dentro del subgrafo del empleado
      const inSub = empSubgraph.edges.some(s => (s.a === e.a && s.b === e.b) || (s.a === e.b && s.b === e.a));
      if (!inSub) return false;
    }
    return true;
  }), [graph, activeEdgeKinds, activeTypes, nodeById, empSubgraph]);

  const visibleNodes = useMemoRel(() =>
    positioned.filter(n => {
      if (!activeTypes.has(n.kind)) return false;
      if (empSubgraph && !empSubgraph.ids.has(n.id)) return false;
      return true;
    }),
    [positioned, activeTypes, empSubgraph]
  );

  // Counts for the chips
  const counts = useMemoRel(() => {
    const c = { byType: {}, byEdge: {} };
    graph.nodes.forEach(n => c.byType[n.kind] = (c.byType[n.kind] || 0) + 1);
    graph.edges.forEach(e => c.byEdge[e.tipo] = (c.byEdge[e.tipo] || 0) + 1);
    return c;
  }, [graph]);

  // Selected node data
  const selCI = selected ? findCI(selected) : null;
  const selNeighbors = useMemoRel(() => {
    if (!selected) return [];
    const map = new Map();
    graph.edges.forEach(e => {
      if (e.a === selected) {
        const arr = map.get(e.b) || [];
        arr.push(e.tipo);
        map.set(e.b, arr);
      } else if (e.b === selected) {
        const arr = map.get(e.a) || [];
        arr.push(e.tipo);
        map.set(e.a, arr);
      }
    });
    return Array.from(map.entries());
  }, [selected, graph]);

  return (
    <div className="col">
      <Card tight>
        <div className="emp-focus-bar">
          <div className="emp-focus-label">
            <Icon name="user" />
            <span>Enfocar empleado</span>
          </div>
          <div className="emp-focus-controls">
            <select
              className="form-input"
              value={empFocus || ''}
              onChange={e => {
                const v = e.target.value || null;
                setEmpFocus(v);
                setSelected(v); // auto-selecciona en el side panel
              }}
              style={{ minWidth: 280 }}
            >
              <option value="">— Mostrar a todos los empleados —</option>
              {[...D.empleados]
                .filter(e => e.estado === 'activo')
                .sort((a, b) => a.nombre.localeCompare(b.nombre))
                .map(e => (
                  <option key={e.id} value={e.id}>{e.nombre} · {e.area} · {e.id}</option>
                ))}
            </select>
            {empFocus && (
              <>
                <div className="emp-degree-toggle" role="tablist">
                  <button
                    className={empDegree === 1 ? 'on' : ''}
                    onClick={() => setEmpDegree(1)}
                    title="Sólo CIs directamente asignados"
                  >Directos</button>
                  <button
                    className={empDegree === 2 ? 'on' : ''}
                    onClick={() => setEmpDegree(2)}
                    title="Incluye proveedores de cada activo"
                  >+ Proveedores</button>
                </div>
                <EmpFocusStats empId={empFocus} subgraph={empSubgraph} />
                <button
                  className="btn sm"
                  onClick={() => { setEmpFocus(null); setSelected(null); }}
                >
                  <Icon name="x" size={11} /> Quitar enfoque
                </button>
              </>
            )}
            {!empFocus && (
              <span className="mono" style={{ fontSize: 11, color: 'var(--ink-3)' }}>
                Responde: ¿qué CIs tiene asignados este empleado?
              </span>
            )}
          </div>
        </div>

        <div style={{ padding: 12, display: 'flex', gap: 14, alignItems: 'center', flexWrap: 'wrap', borderBottom: '1px solid var(--line)' }}>
          <span className="mono" style={{ fontSize: 11, color: 'var(--ink-3)', textTransform: 'uppercase', letterSpacing: '0.08em' }}>Tipos de CI</span>
          {Object.entries(CI_TYPES).filter(([k]) => k !== 'MNT').map(([k, v]) => (
            <Chip
              key={k}
              on={activeTypes.has(k)}
              onClick={() => setActiveTypes(toggleSet(activeTypes, k))}
              label={v.plural}
              count={counts.byType[k] || 0}
              dotColor={v.color}
            />
          ))}
        </div>
        <div style={{ padding: 12, display: 'flex', gap: 14, alignItems: 'center', flexWrap: 'wrap' }}>
          <span className="mono" style={{ fontSize: 11, color: 'var(--ink-3)', textTransform: 'uppercase', letterSpacing: '0.08em' }}>Tipos de relación</span>
          {Object.entries(EDGE_KINDS).map(([k, v]) => (
            <Chip
              key={k}
              on={activeEdgeKinds.has(k)}
              onClick={() => setActiveEdgeKinds(toggleSet(activeEdgeKinds, k))}
              label={v.label}
              count={counts.byEdge[k] || 0}
              dotColor={v.color}
            />
          ))}
          <div style={{ marginLeft: 'auto', display: 'flex', gap: 8 }}>
            <button className="btn sm" onClick={() => { setSelected(null); }}>Limpiar selección</button>
          </div>
        </div>
      </Card>

      <div style={{ display: 'grid', gridTemplateColumns: '1fr 320px', gap: 18, alignItems: 'start' }}>
        <Card title="Mapa de relaciones" sub={`${visibleNodes.length} nodos · ${visibleEdges.length} aristas`} tight>
          <div className="big-graph">
            <svg className="graph-svg" viewBox="0 0 100 100" preserveAspectRatio="none">
              {/* Sector labels backgrounds */}
              {Object.entries(SECTOR_LAYOUT).map(([k, L]) => {
                if (!activeTypes.has(k)) return null;
                return (
                  <text key={k} x={L.cx} y={L.cy - 14} textAnchor="middle" fill="oklch(75% 0.008 80)" fontSize="2.4" fontWeight="600" fontFamily="IBM Plex Mono, monospace" style={{ textTransform: 'uppercase', letterSpacing: '0.1em' }}>
                    {CI_TYPES[k].plural}
                  </text>
                );
              })}
              {/* Edges */}
              {visibleEdges.map((e, i) => {
                const na = nodeById[e.a], nb = nodeById[e.b];
                if (!na || !nb) return null;
                const isFocus = neighborhood && (neighborhood.has(e.a) && neighborhood.has(e.b));
                const dim = neighborhood && !isFocus;
                return (
                  <line
                    key={i}
                    x1={na.x} y1={na.y} x2={nb.x} y2={nb.y}
                    stroke={EDGE_KINDS[e.tipo].color}
                    strokeWidth={isFocus ? '0.35' : '0.18'}
                    strokeOpacity={dim ? 0.12 : (isFocus ? 0.85 : 0.45)}
                    vectorEffect="non-scaling-stroke"
                  />
                );
              })}
            </svg>

            {/* Nodes */}
            {visibleNodes.map(n => {
              const isFocus = neighborhood && neighborhood.has(n.id);
              const isSelected = selected === n.id;
              const dim = neighborhood && !isFocus;
              const t = CI_TYPES[n.kind];
              return (
                <button
                  key={n.id}
                  className={`gdot ${isSelected ? 'is-sel' : ''} ${dim ? 'dim' : ''} ${isFocus ? 'focus' : ''}`}
                  style={{ left: n.x + '%', top: n.y + '%', '--c': t.color }}
                  onClick={() => setSelected(s => s === n.id ? null : n.id)}
                  onMouseEnter={() => setHover(n.id)}
                  onMouseLeave={() => setHover(null)}
                  title={`${n.id} · ${n.label}`}
                />
              );
            })}

            {/* Floating label for hover/selected */}
            {focusId && nodeById[focusId] && (
              <div className="gtip" style={{
                left: nodeById[focusId].x + '%',
                top: nodeById[focusId].y + '%',
              }}>
                <div className="mono" style={{ fontSize: 10, color: 'var(--ink-3)' }}>{focusId}</div>
                <div style={{ fontSize: 12, fontWeight: 500 }}>{nodeById[focusId].label}</div>
              </div>
            )}
          </div>
        </Card>

        <SidePanel selected={selected} selCI={selCI} neighbors={selNeighbors} nodeById={nodeById} onOpenCI={onOpenCI} onSelect={setSelected} counts={counts} graph={graph} />
      </div>

      <Card title="Tabla de relaciones" sub={`${visibleEdges.length} filtradas de ${graph.edges.length}`} tight>
        <div style={{ maxHeight: 360, overflow: 'auto' }}>
          <table className="tbl">
            <thead>
              <tr>
                <th>Origen</th>
                <th>ID</th>
                <th style={{ width: 24 }}></th>
                <th>Destino</th>
                <th>ID</th>
                <th>Relación</th>
              </tr>
            </thead>
            <tbody>
              {visibleEdges.slice(0, 200).map((e, i) => {
                const na = nodeById[e.a], nb = nodeById[e.b];
                if (!na || !nb) return null;
                return (
                  <tr key={i}>
                    <td>
                      <span style={{ display: 'inline-flex', alignItems: 'center', gap: 6 }}>
                        <span style={{ width: 6, height: 6, borderRadius: '50%', background: CI_TYPES[na.kind].color }} />
                        <span onClick={() => onOpenCI(na.id)} style={{ cursor: 'pointer', textDecoration: 'underline', textDecorationColor: 'var(--line-2)' }}>{na.label}</span>
                      </span>
                    </td>
                    <td className="id">{na.id}</td>
                    <td><Icon name="arrow" size={11}/></td>
                    <td>
                      <span style={{ display: 'inline-flex', alignItems: 'center', gap: 6 }}>
                        <span style={{ width: 6, height: 6, borderRadius: '50%', background: CI_TYPES[nb.kind].color }} />
                        <span onClick={() => onOpenCI(nb.id)} style={{ cursor: 'pointer', textDecoration: 'underline', textDecorationColor: 'var(--line-2)' }}>{nb.label}</span>
                      </span>
                    </td>
                    <td className="id">{nb.id}</td>
                    <td>
                      <Badge>
                        <span style={{ width: 6, height: 6, borderRadius: '50%', background: EDGE_KINDS[e.tipo].color }} />
                        {EDGE_KINDS[e.tipo].label}
                      </Badge>
                    </td>
                  </tr>
                );
              })}
              {visibleEdges.length > 200 && (
                <tr><td colSpan={6}><div className="empty">Mostrando 200 de {visibleEdges.length} relaciones — afina con filtros</div></td></tr>
              )}
            </tbody>
          </table>
        </div>
      </Card>
    </div>
  );
}

function SidePanel({ selected, selCI, neighbors, nodeById, onOpenCI, onSelect, counts, graph }) {
  if (!selected || !selCI || !selCI.data) {
    // Default summary panel
    const D = window.CMDB_DATA;
    return (
      <div className="col" style={{ gap: 12 }}>
        <Card title="Resumen del grafo">
          <div className="stat-row"><span className="k">CIs totales</span><span className="v">{graph.nodes.length}</span></div>
          <div className="stat-row"><span className="k">Relaciones</span><span className="v">{graph.edges.length}</span></div>
          <div className="stat-row"><span className="k">Densidad</span><span className="v">{(graph.edges.length / graph.nodes.length).toFixed(1)} rel/CI</span></div>
          <div className="stat-row"><span className="k">CIs aislados</span><span className="v">{(() => {
            const connected = new Set();
            graph.edges.forEach(e => { connected.add(e.a); connected.add(e.b); });
            return graph.nodes.filter(n => !connected.has(n.id)).length;
          })()}</span></div>
        </Card>
        <Card title="Por tipo de relación">
          <div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
            {Object.entries(counts.byEdge).sort((a,b) => b[1] - a[1]).map(([k, v]) => (
              <div key={k} style={{ display: 'flex', alignItems: 'center', gap: 8, fontSize: 12 }}>
                <span style={{ width: 8, height: 8, borderRadius: '50%', background: EDGE_KINDS[k].color }} />
                <span style={{ flex: 1 }}>{EDGE_KINDS[k].label}</span>
                <span className="mono" style={{ color: 'var(--ink-3)' }}>{v}</span>
              </div>
            ))}
          </div>
        </Card>
        <Card>
          <div className="serif-it" style={{ fontSize: 13, color: 'var(--ink-2)' }}>
            Selecciona un nodo en el grafo para ver sus relaciones directas.
          </div>
        </Card>
      </div>
    );
  }

  const t = CI_TYPES[selCI.kind];
  const d = selCI.data;
  return (
    <div className="col" style={{ gap: 12 }}>
      <Card tight>
        <div style={{ padding: '14px 16px', display: 'flex', alignItems: 'start', gap: 12, borderBottom: '1px solid var(--line)' }}>
          <div style={{ width: 36, height: 36, borderRadius: 6, background: t.color, color: 'white', display: 'grid', placeItems: 'center', flexShrink: 0 }}>
            <Icon name={iconForType(selCI.kind)} size={18} />
          </div>
          <div style={{ minWidth: 0, flex: 1 }}>
            <div className="mono" style={{ fontSize: 11, color: 'var(--ink-3)' }}>{selected} · {t.label}</div>
            <div style={{ fontSize: 14, fontWeight: 600, marginTop: 2, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>{ciLabel(selCI)}</div>
          </div>
        </div>
        <div style={{ padding: '10px 16px', display: 'flex', gap: 8, flexWrap: 'wrap' }}>
          <button className="btn sm" onClick={() => onOpenCI(selected)}>Abrir detalle</button>
          <button className="btn sm ghost" onClick={() => onSelect(null)}>Deseleccionar</button>
        </div>
      </Card>
      <Card title={`Relaciones (${neighbors.length})`} tight>
        {neighbors.length === 0 ? (
          <div className="empty">Sin relaciones registradas</div>
        ) : (
          <div style={{ maxHeight: 420, overflow: 'auto' }}>
            {neighbors.map(([nid, tipos]) => {
              const n = nodeById[nid];
              if (!n) return null;
              const ct = CI_TYPES[n.kind];
              return (
                <div key={nid} className="assignee-row" onClick={() => onSelect(nid)} style={{ gap: 8 }}>
                  <span style={{ width: 8, height: 8, borderRadius: '50%', background: ct.color, flexShrink: 0 }} />
                  <div style={{ minWidth: 0, flex: 1 }}>
                    <div style={{ overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>{n.label}</div>
                    <div className="mono" style={{ fontSize: 10, color: 'var(--ink-3)' }}>{nid}</div>
                  </div>
                  <div style={{ display: 'flex', flexDirection: 'column', alignItems: 'flex-end', gap: 2 }}>
                    {Array.from(new Set(tipos)).map(tp => (
                      <span key={tp} style={{ fontSize: 10, color: EDGE_KINDS[tp].color, fontFamily: 'IBM Plex Mono, monospace' }}>{tp}</span>
                    ))}
                  </div>
                </div>
              );
            })}
          </div>
        )}
      </Card>
    </div>
  );
}

Object.assign(window, { RelationsView });

// Compact stats chip strip for the focused employee
function EmpFocusStats({ empId, subgraph }) {
  const D = window.CMDB_DATA;
  if (!empId || !subgraph) return null;
  const ids = Array.from(subgraph.ids).filter(id => id !== empId);
  const byKind = {};
  ids.forEach(id => {
    const k = id.slice(0, 3);
    byKind[k] = (byKind[k] || 0) + 1;
  });
  const order = ['EQP','LIC','MBX','PRV','SRV','TEL'];
  return (
    <div className="emp-stats">
      {order.map(k => {
        if (!byKind[k]) return null;
        const t = CI_TYPES[k];
        return (
          <div key={k} className="emp-stat">
            <span className="dot" style={{ background: t.color }} />
            <span className="n tnum">{byKind[k]}</span>
            <span className="lbl">{t.plural}</span>
          </div>
        );
      })}
    </div>
  );
}
