// Network view — departments laid out radially with tools clustered around each,
// connection lines drawn from each tool to its secondary departments.

const { useMemo, useState, useRef, useEffect } = React;

function NetworkView({ filter, hover, setHover, onSelect }) {
  // Canvas
  const W = 1280;
  const H = 920;
  const cx = W / 2;
  const cy = H / 2;

  // Use only departments that have tools
  const liveDepts = useMemo(() => {
    const used = new Set(TOOLS.map((t) => t.dept));
    return DEPARTMENTS.filter((d) => used.has(d.id));
  }, []);

  // Position departments on an outer ring
  const ringR = 340;
  const deptPos = useMemo(() => {
    const map = {};
    const n = liveDepts.length;
    liveDepts.forEach((d, i) => {
      const a = (i / n) * Math.PI * 2 - Math.PI / 2;
      map[d.id] = {
        x: cx + Math.cos(a) * ringR,
        y: cy + Math.sin(a) * ringR,
        angle: a,
      };
    });
    return map;
  }, [liveDepts]);

  // Position tools in a fan around their primary department, pushed outward
  const toolPos = useMemo(() => {
    const map = {};
    const groups = {};
    TOOLS.forEach((t) => {
      groups[t.dept] = groups[t.dept] || [];
      groups[t.dept].push(t);
    });
    Object.entries(groups).forEach(([deptId, tools]) => {
      const dp = deptPos[deptId];
      if (!dp) return;
      // sort largest annual first so big logos sit near the dept center
      const sorted = [...tools].sort((a, b) => b.annual - a.annual);
      const baseAngle = dp.angle;
      // Fan outward from the dept node, away from center
      // Tools placed in concentric arcs.
      sorted.forEach((t, idx) => {
        const ringIdx = Math.floor(idx / 5); // up to 5 per arc
        const inRing = sorted.slice(ringIdx * 5, ringIdx * 5 + 5).length;
        const posInRing = idx - ringIdx * 5;
        const arcSpan = Math.min(1.05, 0.45 + inRing * 0.13);
        const arcStart = baseAngle - arcSpan / 2;
        const arcStep = inRing > 1 ? arcSpan / (inRing - 1) : 0;
        const aa = inRing === 1 ? baseAngle : arcStart + posInRing * arcStep;
        const rr = 110 + ringIdx * 78;
        map[t.name] = {
          x: dp.x + Math.cos(aa) * rr,
          y: dp.y + Math.sin(aa) * rr,
        };
      });
    });
    return map;
  }, [deptPos]);

  // Build edges from cross-dept connections
  const edges = useMemo(() => {
    const list = [];
    TOOLS.forEach((t) => {
      (t.connects || []).forEach((deptId) => {
        if (deptId === t.dept) return;
        if (!deptPos[deptId]) return;
        list.push({ tool: t, toDept: deptId });
      });
    });
    return list;
  }, [deptPos]);

  // Highlighting
  const matchesFilter = (tool) => {
    if (!filter || filter === "*") return true;
    return tool.dept === filter || (tool.connects || []).includes(filter);
  };

  const isHoverConnected = (toolName) => {
    if (!hover) return false;
    if (hover.kind === "tool") {
      return hover.id === toolName;
    }
    if (hover.kind === "dept") {
      const t = TOOLS.find((x) => x.name === toolName);
      return t && (t.dept === hover.id || (t.connects || []).includes(hover.id));
    }
    return false;
  };

  const deptHovered = (deptId) => {
    if (!hover) return false;
    if (hover.kind === "dept") return hover.id === deptId;
    if (hover.kind === "tool") {
      const t = TOOLS.find((x) => x.name === hover.id);
      return t && (t.dept === deptId || (t.connects || []).includes(deptId));
    }
    return false;
  };

  const edgeActive = (e) => {
    if (!hover) return false;
    if (hover.kind === "tool") return hover.id === e.tool.name;
    if (hover.kind === "dept")
      return hover.id === e.toDept || hover.id === e.tool.dept;
    return false;
  };

  // Render curves
  const curvePath = (x1, y1, x2, y2) => {
    const mx = (x1 + x2) / 2;
    const my = (y1 + y2) / 2;
    // bend toward center
    const dx = cx - mx;
    const dy = cy - my;
    const dist = Math.hypot(dx, dy);
    const bend = 0.18;
    const cxp = mx + (dx / (dist || 1)) * dist * bend;
    const cyp = my + (dy / (dist || 1)) * dist * bend;
    return `M ${x1} ${y1} Q ${cxp} ${cyp} ${x2} ${y2}`;
  };

  return (
    <div className="net-wrap">
      <svg
        viewBox={`0 0 ${W} ${H}`}
        className="net-svg"
        onClick={() => setHover(null)}
      >
        <defs>
          <radialGradient id="centerGlow" cx="50%" cy="50%" r="50%">
            <stop offset="0%" stopColor="oklch(0.28 0.02 250 / 0.9)" />
            <stop offset="100%" stopColor="oklch(0.16 0.01 250 / 0)" />
          </radialGradient>
        </defs>

        {/* Center glow */}
        <circle cx={cx} cy={cy} r={260} fill="url(#centerGlow)" />

        {/* Faint ring */}
        <circle
          cx={cx}
          cy={cy}
          r={ringR}
          fill="none"
          stroke="oklch(0.32 0.01 250 / 0.5)"
          strokeWidth={1}
          strokeDasharray="2 6"
        />

        {/* Edges */}
        <g>
          {edges.map((e, i) => {
            const tp = toolPos[e.tool.name];
            const dp = deptPos[e.toDept];
            if (!tp || !dp) return null;
            const visible = matchesFilter(e.tool);
            const active = edgeActive(e);
            const color = deptColor(e.toDept, 0.7, 0.13);
            return (
              <path
                key={i}
                d={curvePath(tp.x, tp.y, dp.x, dp.y)}
                fill="none"
                stroke={color}
                strokeWidth={active ? 1.6 : 0.7}
                strokeOpacity={!visible ? 0.04 : active ? 0.9 : 0.18}
                style={{ transition: "stroke-opacity .18s, stroke-width .18s" }}
              />
            );
          })}
        </g>

        {/* Center hub */}
        <g>
          <circle
            cx={cx}
            cy={cy}
            r={62}
            fill="oklch(0.22 0.012 250)"
            stroke="oklch(0.42 0.03 60)"
            strokeWidth={1}
          />
          <text
            x={cx}
            y={cy - 6}
            textAnchor="middle"
            fontFamily="'Inter', system-ui"
            fontSize={16}
            fontWeight={700}
            fill="oklch(0.95 0.005 250)"
            letterSpacing={2}
          >
            ZINTEX
          </text>
          <text
            x={cx}
            y={cy + 14}
            textAnchor="middle"
            fontFamily="'JetBrains Mono', monospace"
            fontSize={10}
            fill="oklch(0.65 0.01 250)"
            letterSpacing={1.5}
          >
            TECH STACK
          </text>
          <text
            x={cx}
            y={cy + 30}
            textAnchor="middle"
            fontFamily="'JetBrains Mono', monospace"
            fontSize={9}
            fill="oklch(0.55 0.01 250)"
            letterSpacing={1}
          >
            FY26
          </text>
        </g>

        {/* Department nodes */}
        <g>
          {liveDepts.map((d) => {
            const p = deptPos[d.id];
            const active = deptHovered(d.id);
            const color = deptColor(d.id, 0.72, 0.13);
            const r = 30 + Math.min(14, STATS.byDept[d.id].count * 1.2);
            return (
              <g
                key={d.id}
                style={{ cursor: "pointer" }}
                onMouseEnter={() => setHover({ kind: "dept", id: d.id })}
                onMouseLeave={() => setHover(null)}
                onClick={(ev) => {
                  ev.stopPropagation();
                  onSelect({ kind: "dept", id: d.id });
                }}
              >
                <circle
                  cx={p.x}
                  cy={p.y}
                  r={r + 8}
                  fill={color}
                  opacity={active ? 0.18 : 0.07}
                />
                <circle
                  cx={p.x}
                  cy={p.y}
                  r={r}
                  fill="oklch(0.22 0.012 250)"
                  stroke={color}
                  strokeWidth={active ? 2.2 : 1.4}
                />
                <text
                  x={p.x}
                  y={p.y - 2}
                  textAnchor="middle"
                  fontFamily="'Inter', system-ui"
                  fontSize={11}
                  fontWeight={700}
                  fill={color}
                  letterSpacing={1.2}
                >
                  {d.short}
                </text>
                <text
                  x={p.x}
                  y={p.y + 12}
                  textAnchor="middle"
                  fontFamily="'JetBrains Mono', monospace"
                  fontSize={9}
                  fill="oklch(0.65 0.01 250)"
                >
                  {STATS.byDept[d.id].count} tools
                </text>
              </g>
            );
          })}
        </g>

        {/* Tool nodes */}
        <g>
          {TOOLS.map((t) => {
            const p = toolPos[t.name];
            if (!p) return null;
            const visible = matchesFilter(t);
            const connected = isHoverConnected(t.name);
            const dim = !visible || (hover && !connected);
            const size = 12 + Math.min(18, Math.log10(Math.max(t.annual, 100)) * 4);
            return (
              <g
                key={t.name}
                style={{
                  cursor: "pointer",
                  opacity: dim ? 0.18 : 1,
                  transition: "opacity .18s",
                }}
                onMouseEnter={() => setHover({ kind: "tool", id: t.name })}
                onMouseLeave={() => setHover(null)}
                onClick={(ev) => {
                  ev.stopPropagation();
                  onSelect({ kind: "tool", id: t.name });
                }}
              >
                <foreignObject
                  x={p.x - size / 2}
                  y={p.y - size / 2}
                  width={size}
                  height={size}
                >
                  <div
                    style={{
                      width: size,
                      height: size,
                      borderRadius: Math.round(size * 0.24),
                      boxShadow: connected
                        ? "0 0 0 2px oklch(0.95 0.005 250 / 0.9), 0 4px 18px oklch(0 0 0 / 0.5)"
                        : "0 2px 8px oklch(0 0 0 / 0.5)",
                      transition: "box-shadow .18s",
                      overflow: "hidden",
                    }}
                  >
                    <LogoTile tool={t} size={size} radius={Math.round(size * 0.24)} />
                  </div>
                </foreignObject>
                {connected && (
                  <g>
                    <rect
                      x={p.x + size / 2 + 6}
                      y={p.y - 10}
                      width={t.name.length * 6.2 + 12}
                      height={20}
                      rx={4}
                      fill="oklch(0.16 0.01 250 / 0.95)"
                      stroke="oklch(0.32 0.015 250)"
                      strokeWidth={1}
                    />
                    <text
                      x={p.x + size / 2 + 12}
                      y={p.y + 4}
                      fontFamily="'Inter', system-ui"
                      fontSize={11}
                      fontWeight={600}
                      fill="oklch(0.95 0.005 250)"
                    >
                      {t.name}
                    </text>
                  </g>
                )}
              </g>
            );
          })}
        </g>
      </svg>
    </div>
  );
}

window.NetworkView = NetworkView;
