<script lang="ts" setup>
import { onMounted, onUnmounted, ref } from 'vue'

interface Props {
  nodeCount?: number
  primaryColor?: string
  secondaryColor?: string
}

const props = withDefaults(defineProps<Props>(), {
  nodeCount: 8,
  primaryColor: '#3b82f6',
  secondaryColor: '#06b6d4',
})

const svgRef = ref<SVGSVGElement | null>(null)

interface Node {
  x: number
  y: number
  r: number
  vx: number
  vy: number
  color: string
  pulseDelay: number
}

const nodes = ref<Node[]>([])
let animFrame = 0

function initNodes(): void {
  nodes.value = Array.from({ length: props.nodeCount }, (_, i) => ({
    x: 50 + Math.random() * 300,
    y: 30 + Math.random() * 240,
    r: 4 + Math.random() * 4,
    vx: (Math.random() - 0.5) * 0.3,
    vy: (Math.random() - 0.5) * 0.3,
    color: i % 3 === 0 ? props.secondaryColor : props.primaryColor,
    pulseDelay: Math.random() * 3,
  }))
}

function animate(): void {
  nodes.value.forEach(node => {
    node.x += node.vx
    node.y += node.vy
    if (node.x < 30 || node.x > 370) node.vx *= -1
    if (node.y < 20 || node.y > 280) node.vy *= -1
  })
  animFrame = requestAnimationFrame(animate)
}

onMounted(() => {
  initNodes()
  animate()
})

onUnmounted(() => {
  cancelAnimationFrame(animFrame)
})

function getDistance(a: Node, b: Node): number {
  return Math.sqrt((a.x - b.x) ** 2 + (a.y - b.y) ** 2)
}
</script>

<template>
  <svg
    ref="svgRef"
    viewBox="0 0 400 300"
    class="network-hero"
    style="width: 100%; height: auto; max-height: 400px;"
  >
    <!-- Connection lines -->
    <template v-for="(node, i) in nodes" :key="'line-' + i">
      <line
        v-for="(other, j) in nodes.slice(i + 1)"
        :key="'conn-' + i + '-' + j"
        :x1="node.x"
        :y1="node.y"
        :x2="other.x"
        :y2="other.y"
        :stroke="node.color"
        :stroke-opacity="Math.max(0, 1 - getDistance(node, other) / 150) * 0.3"
        stroke-width="1"
      />
    </template>

    <!-- Nodes -->
    <g v-for="(node, i) in nodes" :key="'node-' + i">
      <!-- Pulse ring -->
      <circle
        :cx="node.x"
        :cy="node.y"
        :r="node.r * 2.5"
        fill="none"
        :stroke="node.color"
        stroke-width="1"
        opacity="0.15"
      >
        <animate
          attributeName="r"
          :values="`${node.r * 1.5};${node.r * 3};${node.r * 1.5}`"
          :dur="`${2 + node.pulseDelay}s`"
          repeatCount="indefinite"
        />
        <animate
          attributeName="opacity"
          values="0.2;0.05;0.2"
          :dur="`${2 + node.pulseDelay}s`"
          repeatCount="indefinite"
        />
      </circle>
      <!-- Node -->
      <circle
        :cx="node.x"
        :cy="node.y"
        :r="node.r"
        :fill="node.color"
        :opacity="0.8"
      />
    </g>
  </svg>
</template>
