'use client'

import { useState, useEffect, useMemo, useCallback } from 'react'
import type { FlowNode, FunnelNodeData, OutcomeNodeData, SourceNodeData } from '@/lib/types'

// ─── Layout Types ────────────────────────────────────────

interface RiverLayout {
  sources: SourceLayout[]
  funnels: FunnelLayout[]
  outcomes: OutcomeLayout[]
  sourceWaterfalls: WaterfallLayout[]
  overflowBranches: BranchLayout[]
  spendingWaterfalls: WaterfallLayout[]
  width: number
  height: number
}

interface SourceLayout {
  id: string
  label: string
  flowRate: number
  x: number
  y: number
  width: number
}

interface FunnelLayout {
  id: string
  label: string
  data: FunnelNodeData
  x: number
  y: number
  riverWidth: number
  segmentLength: number
  layer: number
  status: 'healthy' | 'overflow' | 'critical'
}

interface OutcomeLayout {
  id: string
  label: string
  data: OutcomeNodeData
  x: number
  y: number
  poolWidth: number
  fillPercent: number
}

interface WaterfallLayout {
  id: string
  sourceId: string
  targetId: string
  label: string
  percentage: number
  x: number
  yStart: number
  yEnd: number
  width: number
  color: string
  flowAmount: number
}

interface BranchLayout {
  sourceId: string
  targetId: string
  percentage: number
  x1: number
  y1: number
  x2: number
  y2: number
  width: number
  color: string
}

// ─── Constants ───────────────────────────────────────────

const LAYER_HEIGHT = 160
const WATERFALL_HEIGHT = 100
const GAP = 40
const MIN_RIVER_WIDTH = 24
const MAX_RIVER_WIDTH = 100
const SEGMENT_LENGTH = 200
const POOL_WIDTH = 100
const POOL_HEIGHT = 60
const SOURCE_HEIGHT = 40

const COLORS = {
  sourceWaterfall: '#10b981',
  riverHealthy: ['#0ea5e9', '#06b6d4'],
  riverOverflow: ['#f59e0b', '#fbbf24'],
  riverCritical: ['#ef4444', '#f87171'],
  overflowBranch: '#f59e0b',
  spendingWaterfall: ['#8b5cf6', '#ec4899', '#06b6d4', '#3b82f6', '#10b981', '#6366f1'],
  outcomePool: '#3b82f6',
  bg: '#0f172a',
  text: '#e2e8f0',
  textMuted: '#94a3b8',
}

// ─── Layout Engine ───────────────────────────────────────

function computeLayout(nodes: FlowNode[]): RiverLayout {
  const funnelNodes = nodes.filter(n => n.type === 'funnel')
  const outcomeNodes = nodes.filter(n => n.type === 'outcome')
  const sourceNodes = nodes.filter(n => n.type === 'source')

  // Build adjacency: which funnels are children (overflow targets) of which
  const overflowTargets = new Set<string>()
  const spendingTargets = new Set<string>()
  const sourceTargets = new Set<string>()

  funnelNodes.forEach(n => {
    const data = n.data as FunnelNodeData
    data.overflowAllocations?.forEach(a => overflowTargets.add(a.targetId))
    data.spendingAllocations?.forEach(a => spendingTargets.add(a.targetId))
  })
  sourceNodes.forEach(n => {
    const data = n.data as SourceNodeData
    data.targetAllocations?.forEach(a => sourceTargets.add(a.targetId))
  })

  // Root funnels = funnels that are NOT overflow targets of other funnels
  // (but may be source targets)
  const rootFunnels = funnelNodes.filter(n => !overflowTargets.has(n.id))
  const childFunnels = funnelNodes.filter(n => overflowTargets.has(n.id))

  // Assign layers
  const funnelLayers = new Map<string, number>()
  rootFunnels.forEach(n => funnelLayers.set(n.id, 0))

  // BFS to assign layers to overflow children
  const queue = [...rootFunnels]
  while (queue.length > 0) {
    const current = queue.shift()!
    const data = current.data as FunnelNodeData
    const parentLayer = funnelLayers.get(current.id) ?? 0
    data.overflowAllocations?.forEach(a => {
      const child = funnelNodes.find(n => n.id === a.targetId)
      if (child && !funnelLayers.has(child.id)) {
        funnelLayers.set(child.id, parentLayer + 1)
        queue.push(child)
      }
    })
  }

  // Find max flow rate for normalization
  const allFlowRates = funnelNodes.map(n => (n.data as FunnelNodeData).inflowRate || 1)
  const maxFlowRate = Math.max(...allFlowRates, 1)
  const maxValue = Math.max(...funnelNodes.map(n => (n.data as FunnelNodeData).currentValue || 1), 1)

  // Compute funnel layouts
  // Group by layer, center each layer
  const layerGroups = new Map<number, FlowNode[]>()
  funnelNodes.forEach(n => {
    const layer = funnelLayers.get(n.id) ?? 0
    if (!layerGroups.has(layer)) layerGroups.set(layer, [])
    layerGroups.get(layer)!.push(n)
  })

  const maxLayer = Math.max(...Array.from(layerGroups.keys()), 0)
  const sourceLayerY = GAP
  const funnelStartY = sourceLayerY + SOURCE_HEIGHT + WATERFALL_HEIGHT + GAP

  const funnelLayouts: FunnelLayout[] = []
  const layerXRanges = new Map<number, { minX: number; maxX: number }>()

  for (let layer = 0; layer <= maxLayer; layer++) {
    const layerNodes = layerGroups.get(layer) || []
    const layerY = funnelStartY + layer * (LAYER_HEIGHT + WATERFALL_HEIGHT + GAP)
    const totalWidth = layerNodes.length * SEGMENT_LENGTH + (layerNodes.length - 1) * GAP * 2

    layerNodes.forEach((n, i) => {
      const data = n.data as FunnelNodeData
      const fillRatio = Math.min(1, data.currentValue / (data.maxCapacity || 1))
      const riverWidth = MIN_RIVER_WIDTH + fillRatio * (MAX_RIVER_WIDTH - MIN_RIVER_WIDTH)
      const x = -totalWidth / 2 + i * (SEGMENT_LENGTH + GAP * 2)
      const status: 'healthy' | 'overflow' | 'critical' =
        data.currentValue > data.maxThreshold ? 'overflow' :
        data.currentValue < data.minThreshold ? 'critical' : 'healthy'

      funnelLayouts.push({
        id: n.id,
        label: data.label,
        data,
        x,
        y: layerY,
        riverWidth,
        segmentLength: SEGMENT_LENGTH,
        layer,
        status,
      })

      const range = layerXRanges.get(layer) || { minX: Infinity, maxX: -Infinity }
      range.minX = Math.min(range.minX, x)
      range.maxX = Math.max(range.maxX, x + SEGMENT_LENGTH)
      layerXRanges.set(layer, range)
    })
  }

  // Source layouts
  const sourceLayouts: SourceLayout[] = sourceNodes.map((n, i) => {
    const data = n.data as SourceNodeData
    const totalWidth = sourceNodes.length * 120 + (sourceNodes.length - 1) * GAP
    return {
      id: n.id,
      label: data.label,
      flowRate: data.flowRate,
      x: -totalWidth / 2 + i * (120 + GAP),
      y: sourceLayerY,
      width: 120,
    }
  })

  // Source waterfalls (source → root funnel)
  const sourceWaterfalls: WaterfallLayout[] = []
  sourceNodes.forEach(sn => {
    const data = sn.data as SourceNodeData
    const sourceLayout = sourceLayouts.find(s => s.id === sn.id)
    if (!sourceLayout) return

    data.targetAllocations?.forEach((alloc, i) => {
      const targetLayout = funnelLayouts.find(f => f.id === alloc.targetId)
      if (!targetLayout) return

      const flowAmount = (alloc.percentage / 100) * data.flowRate
      const width = Math.max(6, (flowAmount / Math.max(data.flowRate, 1)) * 30)

      sourceWaterfalls.push({
        id: `src-wf-${sn.id}-${alloc.targetId}`,
        sourceId: sn.id,
        targetId: alloc.targetId,
        label: `${alloc.percentage}%`,
        percentage: alloc.percentage,
        x: sourceLayout.x + sourceLayout.width / 2 + (i - (data.targetAllocations.length - 1) / 2) * 30,
        yStart: sourceLayout.y + SOURCE_HEIGHT,
        yEnd: targetLayout.y,
        width,
        color: COLORS.sourceWaterfall,
        flowAmount,
      })
    })
  })

  // If no source nodes, create implicit waterfalls for root funnels with inflowRate
  if (sourceNodes.length === 0) {
    rootFunnels.forEach(rn => {
      const data = rn.data as FunnelNodeData
      if (data.inflowRate <= 0) return
      const layout = funnelLayouts.find(f => f.id === rn.id)
      if (!layout) return

      sourceWaterfalls.push({
        id: `implicit-wf-${rn.id}`,
        sourceId: 'implicit',
        targetId: rn.id,
        label: `$${Math.floor(data.inflowRate)}/mo`,
        percentage: 100,
        x: layout.x + layout.segmentLength / 2,
        yStart: GAP,
        yEnd: layout.y,
        width: Math.max(8, (data.inflowRate / maxFlowRate) * 30),
        color: COLORS.sourceWaterfall,
        flowAmount: data.inflowRate,
      })
    })
  }

  // Overflow branches (funnel → child funnel)
  const overflowBranches: BranchLayout[] = []
  funnelNodes.forEach(n => {
    const data = n.data as FunnelNodeData
    const parentLayout = funnelLayouts.find(f => f.id === n.id)
    if (!parentLayout) return

    data.overflowAllocations?.forEach((alloc, i) => {
      const childLayout = funnelLayouts.find(f => f.id === alloc.targetId)
      if (!childLayout) return

      const flowAmount = (alloc.percentage / 100) * (data.inflowRate || 1)
      const width = Math.max(4, (alloc.percentage / 100) * parentLayout.riverWidth * 0.6)

      overflowBranches.push({
        sourceId: n.id,
        targetId: alloc.targetId,
        percentage: alloc.percentage,
        x1: parentLayout.x + parentLayout.segmentLength,
        y1: parentLayout.y + parentLayout.riverWidth / 2,
        x2: childLayout.x,
        y2: childLayout.y + childLayout.riverWidth / 2,
        width,
        color: alloc.color || COLORS.overflowBranch,
      })
    })
  })

  // Outcome layouts
  const outcomeY = funnelStartY + (maxLayer + 1) * (LAYER_HEIGHT + WATERFALL_HEIGHT + GAP) + WATERFALL_HEIGHT
  const totalOutcomeWidth = outcomeNodes.length * (POOL_WIDTH + GAP) - GAP
  const outcomeLayouts: OutcomeLayout[] = outcomeNodes.map((n, i) => {
    const data = n.data as OutcomeNodeData
    const fillPercent = data.fundingTarget > 0
      ? Math.min(100, (data.fundingReceived / data.fundingTarget) * 100)
      : 0

    return {
      id: n.id,
      label: data.label,
      data,
      x: -totalOutcomeWidth / 2 + i * (POOL_WIDTH + GAP),
      y: outcomeY,
      poolWidth: POOL_WIDTH,
      fillPercent,
    }
  })

  // Spending waterfalls (funnel → outcome)
  const spendingWaterfalls: WaterfallLayout[] = []
  funnelNodes.forEach(n => {
    const data = n.data as FunnelNodeData
    const parentLayout = funnelLayouts.find(f => f.id === n.id)
    if (!parentLayout) return

    data.spendingAllocations?.forEach((alloc, i) => {
      const outcomeLayout = outcomeLayouts.find(o => o.id === alloc.targetId)
      if (!outcomeLayout) return

      const flowAmount = (alloc.percentage / 100) * (data.inflowRate || 1)
      const width = Math.max(4, (alloc.percentage / 100) * 24)

      spendingWaterfalls.push({
        id: `spend-wf-${n.id}-${alloc.targetId}`,
        sourceId: n.id,
        targetId: alloc.targetId,
        label: `${alloc.percentage}%`,
        percentage: alloc.percentage,
        x: parentLayout.x + parentLayout.segmentLength / 2 +
          (i - ((data.spendingAllocations?.length || 1) - 1) / 2) * 24,
        yStart: parentLayout.y + parentLayout.riverWidth + 4,
        yEnd: outcomeLayout.y,
        width,
        color: alloc.color || COLORS.spendingWaterfall[i % COLORS.spendingWaterfall.length],
        flowAmount,
      })
    })
  })

  // Compute total bounds
  const allX = [
    ...funnelLayouts.map(f => f.x),
    ...funnelLayouts.map(f => f.x + f.segmentLength),
    ...outcomeLayouts.map(o => o.x),
    ...outcomeLayouts.map(o => o.x + o.poolWidth),
    ...sourceLayouts.map(s => s.x),
    ...sourceLayouts.map(s => s.x + s.width),
  ]
  const allY = [
    ...funnelLayouts.map(f => f.y + f.riverWidth),
    ...outcomeLayouts.map(o => o.y + POOL_HEIGHT),
    sourceLayerY,
  ]

  const minX = Math.min(...allX, -100)
  const maxX = Math.max(...allX, 100)
  const maxY = Math.max(...allY, 400)
  const padding = 80

  // Shift everything so minX starts at padding
  const offsetX = -minX + padding
  const offsetY = padding

  // Apply offsets
  funnelLayouts.forEach(f => { f.x += offsetX; f.y += offsetY })
  outcomeLayouts.forEach(o => { o.x += offsetX; o.y += offsetY })
  sourceLayouts.forEach(s => { s.x += offsetX; s.y += offsetY })
  sourceWaterfalls.forEach(w => { w.x += offsetX; w.yStart += offsetY; w.yEnd += offsetY })
  overflowBranches.forEach(b => { b.x1 += offsetX; b.y1 += offsetY; b.x2 += offsetX; b.y2 += offsetY })
  spendingWaterfalls.forEach(w => { w.x += offsetX; w.yStart += offsetY; w.yEnd += offsetY })

  return {
    sources: sourceLayouts,
    funnels: funnelLayouts,
    outcomes: outcomeLayouts,
    sourceWaterfalls,
    overflowBranches,
    spendingWaterfalls,
    width: maxX - minX + padding * 2,
    height: maxY + offsetY + padding,
  }
}

// ─── SVG Sub-components ──────────────────────────────────

function WaterfallStream({ wf, index }: { wf: WaterfallLayout; index: number }) {
  const height = wf.yEnd - wf.yStart
  const numDroplets = Math.max(3, Math.min(8, Math.floor(wf.width / 3)))

  return (
    <g>
      {/* Main water stream */}
      <defs>
        <linearGradient id={`wf-grad-${wf.id}`} x1="0" y1="0" x2="0" y2="1">
          <stop offset="0%" stopColor={wf.color} stopOpacity="0.9" />
          <stop offset="50%" stopColor={wf.color} stopOpacity="0.6" />
          <stop offset="100%" stopColor={wf.color} stopOpacity="0.3" />
        </linearGradient>
        <clipPath id={`wf-clip-${wf.id}`}>
          <rect x={wf.x - wf.width / 2} y={wf.yStart} width={wf.width} height={height} />
        </clipPath>
      </defs>

      {/* Glow behind */}
      <rect
        x={wf.x - wf.width / 2 - 3}
        y={wf.yStart}
        width={wf.width + 6}
        height={height}
        rx={wf.width / 2}
        fill={wf.color}
        opacity={0.12}
      />

      {/* Animated water strips */}
      <g clipPath={`url(#wf-clip-${wf.id})`}>
        {[0, 1, 2].map(i => (
          <rect
            key={i}
            x={wf.x - wf.width / 2 + 1}
            y={wf.yStart - height}
            width={wf.width - 2}
            height={height}
            fill={`url(#wf-grad-${wf.id})`}
            rx={2}
            style={{
              animation: `waterFlow ${1.2 + i * 0.3}s linear infinite`,
              animationDelay: `${i * -0.4}s`,
            }}
          />
        ))}
      </g>

      {/* Side mist lines */}
      <line
        x1={wf.x - wf.width / 2 - 1}
        y1={wf.yStart}
        x2={wf.x - wf.width / 2 - 1}
        y2={wf.yEnd}
        stroke={wf.color}
        strokeWidth={1}
        opacity={0.3}
        strokeDasharray="4 6"
        style={{ animation: `riverCurrent 1s linear infinite` }}
      />
      <line
        x1={wf.x + wf.width / 2 + 1}
        y1={wf.yStart}
        x2={wf.x + wf.width / 2 + 1}
        y2={wf.yEnd}
        stroke={wf.color}
        strokeWidth={1}
        opacity={0.3}
        strokeDasharray="4 6"
        style={{ animation: `riverCurrent 1s linear infinite` }}
      />

      {/* Droplets */}
      {Array.from({ length: numDroplets }, (_, i) => {
        const dx = (Math.random() - 0.5) * (wf.width + 10)
        const delay = Math.random() * 2
        const dur = 1 + Math.random() * 1.5
        return (
          <circle
            key={`drop-${wf.id}-${i}`}
            cx={wf.x + dx}
            cy={wf.yEnd - 10}
            r={1.5}
            fill={wf.color}
            opacity={0.6}
            style={{
              animation: `droplet ${dur}s ease-in infinite`,
              animationDelay: `${delay}s`,
            }}
          />
        )
      })}

      {/* Splash ripples at bottom */}
      {[0, 1, 2].map(i => (
        <circle
          key={`ripple-${wf.id}-${i}`}
          cx={wf.x}
          cy={wf.yEnd}
          r={2}
          fill="none"
          stroke={wf.color}
          strokeWidth={1}
          style={{
            animation: `ripple 2s ease-out infinite`,
            animationDelay: `${i * 0.6}s`,
          }}
        />
      ))}

      {/* Label */}
      <text
        x={wf.x}
        y={wf.yStart + height / 2}
        textAnchor="middle"
        fill={COLORS.text}
        fontSize={9}
        fontWeight={600}
        fontFamily="monospace"
      >
        {wf.label}
      </text>
    </g>
  )
}

function RiverSegment({ funnel }: { funnel: FunnelLayout }) {
  const { id, label, data, x, y, riverWidth, segmentLength, status } = funnel
  const gradColors = status === 'overflow' ? COLORS.riverOverflow :
    status === 'critical' ? COLORS.riverCritical : COLORS.riverHealthy

  const fillPercent = Math.min(100, (data.currentValue / (data.maxCapacity || 1)) * 100)
  const thresholdMinY = y + riverWidth * 0.85
  const thresholdMaxY = y + riverWidth * 0.15

  return (
    <g>
      <defs>
        <linearGradient id={`river-grad-${id}`} x1="0" y1="0" x2="1" y2="0">
          <stop offset="0%" stopColor={gradColors[0]} stopOpacity="0.6" />
          <stop offset="30%" stopColor={gradColors[0]} stopOpacity="0.9" />
          <stop offset="70%" stopColor={gradColors[1]} stopOpacity="0.9" />
          <stop offset="100%" stopColor={gradColors[1]} stopOpacity="0.6" />
        </linearGradient>
      </defs>

      {/* River glow */}
      <rect
        x={x - 4}
        y={y - 4}
        width={segmentLength + 8}
        height={riverWidth + 8}
        rx={riverWidth / 2 + 4}
        fill={gradColors[0]}
        opacity={0.1}
      />

      {/* River body */}
      <rect
        x={x}
        y={y}
        width={segmentLength}
        height={riverWidth}
        rx={riverWidth / 2}
        fill={`url(#river-grad-${id})`}
      />

      {/* Surface current lines */}
      {[0.3, 0.5, 0.7].map((pos, i) => (
        <line
          key={`current-${id}-${i}`}
          x1={x + 10}
          y1={y + riverWidth * pos}
          x2={x + segmentLength - 10}
          y2={y + riverWidth * pos}
          stroke="rgba(255,255,255,0.25)"
          strokeWidth={1}
          strokeDasharray="8 12"
          style={{
            animation: `riverCurrent ${1.5 + i * 0.3}s linear infinite`,
          }}
        />
      ))}

      {/* Shimmer highlight */}
      <ellipse
        cx={x + segmentLength * 0.4}
        cy={y + riverWidth * 0.3}
        rx={segmentLength * 0.15}
        ry={riverWidth * 0.12}
        fill="rgba(255,255,255,0.15)"
        style={{ animation: 'shimmer 3s ease-in-out infinite' }}
      />

      {/* Threshold markers */}
      <line
        x1={x + 5}
        y1={thresholdMaxY}
        x2={x + segmentLength - 5}
        y2={thresholdMaxY}
        stroke="#f59e0b"
        strokeWidth={1.5}
        strokeDasharray="4 3"
        opacity={0.6}
      />
      <text x={x + segmentLength + 6} y={thresholdMaxY + 3} fontSize={7} fill="#f59e0b" fontWeight="bold">MAX</text>

      <line
        x1={x + 5}
        y1={thresholdMinY}
        x2={x + segmentLength - 5}
        y2={thresholdMinY}
        stroke="#ef4444"
        strokeWidth={1.5}
        strokeDasharray="4 3"
        opacity={0.6}
      />
      <text x={x + segmentLength + 6} y={thresholdMinY + 3} fontSize={7} fill="#ef4444" fontWeight="bold">MIN</text>

      {/* Label */}
      <text
        x={x + segmentLength / 2}
        y={y - 10}
        textAnchor="middle"
        fill={COLORS.text}
        fontSize={12}
        fontWeight={700}
      >
        {label}
      </text>

      {/* Value */}
      <text
        x={x + segmentLength / 2}
        y={y + riverWidth / 2 + 4}
        textAnchor="middle"
        fill="white"
        fontSize={13}
        fontWeight={700}
        fontFamily="monospace"
      >
        ${Math.floor(data.currentValue).toLocaleString()}
      </text>

      {/* Status pill */}
      <rect
        x={x + segmentLength / 2 - 16}
        y={y + riverWidth + 6}
        width={32}
        height={14}
        rx={7}
        fill={status === 'overflow' ? '#f59e0b' : status === 'critical' ? '#ef4444' : '#10b981'}
        opacity={0.9}
      />
      <text
        x={x + segmentLength / 2}
        y={y + riverWidth + 16}
        textAnchor="middle"
        fill="white"
        fontSize={7}
        fontWeight={700}
      >
        {status === 'overflow' ? 'OVER' : status === 'critical' ? 'LOW' : 'OK'}
      </text>
    </g>
  )
}

function OverflowBranch({ branch }: { branch: BranchLayout }) {
  const { x1, y1, x2, y2, width, color, percentage } = branch
  const midX = (x1 + x2) / 2
  const midY = (y1 + y2) / 2

  // Curved path connecting two river segments
  const path = `M ${x1} ${y1} C ${x1 + 60} ${y1}, ${x2 - 60} ${y2}, ${x2} ${y2}`

  return (
    <g>
      {/* Glow */}
      <path
        d={path}
        fill="none"
        stroke={color}
        strokeWidth={width + 6}
        opacity={0.1}
        strokeLinecap="round"
      />
      {/* Main branch */}
      <path
        d={path}
        fill="none"
        stroke={color}
        strokeWidth={width}
        opacity={0.7}
        strokeLinecap="round"
        strokeDasharray="10 5"
        style={{ animation: `riverCurrent 1.5s linear infinite` }}
      />
      {/* Flow direction arrows */}
      <text
        x={midX}
        y={midY - width / 2 - 4}
        textAnchor="middle"
        fill={color}
        fontSize={9}
        fontWeight={600}
        fontFamily="monospace"
      >
        {percentage}%
      </text>
    </g>
  )
}

function OutcomePool({ outcome }: { outcome: OutcomeLayout }) {
  const { id, label, data, x, y, poolWidth, fillPercent } = outcome
  const fillHeight = (fillPercent / 100) * POOL_HEIGHT

  const statusColor =
    data.status === 'completed' ? '#10b981' :
    data.status === 'in-progress' ? '#3b82f6' :
    data.status === 'blocked' ? '#ef4444' : '#64748b'

  return (
    <g>
      {/* Pool container */}
      <rect
        x={x}
        y={y}
        width={poolWidth}
        height={POOL_HEIGHT}
        rx={8}
        fill="rgba(15,23,42,0.8)"
        stroke={statusColor}
        strokeWidth={1.5}
        opacity={0.9}
      />

      {/* Water fill */}
      <defs>
        <clipPath id={`pool-clip-${id}`}>
          <rect x={x + 2} y={y + 2} width={poolWidth - 4} height={POOL_HEIGHT - 4} rx={6} />
        </clipPath>
        <linearGradient id={`pool-grad-${id}`} x1="0" y1="1" x2="0" y2="0">
          <stop offset="0%" stopColor={statusColor} stopOpacity="0.8" />
          <stop offset="100%" stopColor={statusColor} stopOpacity="0.4" />
        </linearGradient>
      </defs>

      <g clipPath={`url(#pool-clip-${id})`}>
        <rect
          x={x + 2}
          y={y + POOL_HEIGHT - fillHeight}
          width={poolWidth - 4}
          height={fillHeight}
          fill={`url(#pool-grad-${id})`}
        />
        {/* Water surface wave */}
        {fillPercent > 5 && (
          <ellipse
            cx={x + poolWidth / 2}
            cy={y + POOL_HEIGHT - fillHeight}
            rx={poolWidth * 0.3}
            ry={2}
            fill="rgba(255,255,255,0.2)"
            style={{ animation: 'waveFloat 2s ease-in-out infinite' }}
          />
        )}
      </g>

      {/* Label */}
      <text
        x={x + poolWidth / 2}
        y={y - 6}
        textAnchor="middle"
        fill={COLORS.text}
        fontSize={9}
        fontWeight={600}
      >
        {label}
      </text>

      {/* Value */}
      <text
        x={x + poolWidth / 2}
        y={y + POOL_HEIGHT / 2 + 2}
        textAnchor="middle"
        fill="white"
        fontSize={9}
        fontWeight={600}
        fontFamily="monospace"
      >
        ${Math.floor(data.fundingReceived).toLocaleString()}
      </text>

      {/* Progress */}
      <text
        x={x + poolWidth / 2}
        y={y + POOL_HEIGHT / 2 + 14}
        textAnchor="middle"
        fill={COLORS.textMuted}
        fontSize={7}
        fontFamily="monospace"
      >
        {Math.round(fillPercent)}% of ${Math.floor(data.fundingTarget).toLocaleString()}
      </text>
    </g>
  )
}

function SourceBox({ source }: { source: SourceLayout }) {
  return (
    <g>
      <rect
        x={source.x}
        y={source.y}
        width={source.width}
        height={SOURCE_HEIGHT}
        rx={8}
        fill="rgba(16,185,129,0.15)"
        stroke="#10b981"
        strokeWidth={1.5}
      />
      <text
        x={source.x + source.width / 2}
        y={source.y + SOURCE_HEIGHT / 2 - 4}
        textAnchor="middle"
        fill="#10b981"
        fontSize={10}
        fontWeight={700}
      >
        {source.label}
      </text>
      <text
        x={source.x + source.width / 2}
        y={source.y + SOURCE_HEIGHT / 2 + 10}
        textAnchor="middle"
        fill="#10b981"
        fontSize={8}
        fontFamily="monospace"
        opacity={0.7}
      >
        ${source.flowRate.toLocaleString()}/mo
      </text>
    </g>
  )
}

// ─── Main Component ──────────────────────────────────────

interface BudgetRiverProps {
  nodes: FlowNode[]
  isSimulating?: boolean
}

export default function BudgetRiver({ nodes, isSimulating = false }: BudgetRiverProps) {
  const [animatedNodes, setAnimatedNodes] = useState<FlowNode[]>(nodes)

  // Update when parent nodes change
  useEffect(() => {
    setAnimatedNodes(nodes)
  }, [nodes])

  // Simulation
  useEffect(() => {
    if (!isSimulating) return

    const interval = setInterval(() => {
      setAnimatedNodes(prev =>
        prev.map(node => {
          if (node.type === 'funnel') {
            const data = node.data as FunnelNodeData
            const change = (Math.random() - 0.45) * 300
            return {
              ...node,
              data: {
                ...data,
                currentValue: Math.max(0, Math.min(data.maxCapacity * 1.1, data.currentValue + change)),
              },
            }
          } else if (node.type === 'outcome') {
            const data = node.data as OutcomeNodeData
            const change = Math.random() * 80
            const newReceived = Math.min(data.fundingTarget * 1.05, data.fundingReceived + change)
            return {
              ...node,
              data: {
                ...data,
                fundingReceived: newReceived,
                status: newReceived >= data.fundingTarget ? 'completed' :
                  data.status === 'not-started' && newReceived > 0 ? 'in-progress' : data.status,
              },
            }
          }
          return node
        })
      )
    }, 500)

    return () => clearInterval(interval)
  }, [isSimulating])

  const layout = useMemo(() => computeLayout(animatedNodes), [animatedNodes])

  return (
    <div className="w-full h-full overflow-auto">
      <svg
        width={layout.width}
        height={layout.height}
        viewBox={`0 0 ${layout.width} ${layout.height}`}
        className="mx-auto"
        style={{ minWidth: layout.width, minHeight: layout.height }}
      >
        {/* Background */}
        <rect width={layout.width} height={layout.height} fill={COLORS.bg} />

        {/* Background stars/dots for atmosphere */}
        {Array.from({ length: 30 }, (_, i) => (
          <circle
            key={`star-${i}`}
            cx={Math.random() * layout.width}
            cy={Math.random() * layout.height}
            r={0.5 + Math.random() * 1}
            fill="rgba(148,163,184,0.2)"
            style={{
              animation: `shimmer ${2 + Math.random() * 3}s ease-in-out infinite`,
              animationDelay: `${Math.random() * 3}s`,
            }}
          />
        ))}

        {/* Layer 1: Source boxes */}
        {layout.sources.map(s => (
          <SourceBox key={s.id} source={s} />
        ))}

        {/* Layer 2: Source waterfalls (flowing into river) */}
        {layout.sourceWaterfalls.map((wf, i) => (
          <WaterfallStream key={wf.id} wf={wf} index={i} />
        ))}

        {/* Layer 3: River segments */}
        {layout.funnels.map(f => (
          <RiverSegment key={f.id} funnel={f} />
        ))}

        {/* Layer 4: Overflow branches */}
        {layout.overflowBranches.map((b, i) => (
          <OverflowBranch key={`overflow-${i}`} branch={b} />
        ))}

        {/* Layer 5: Spending waterfalls (flowing out) */}
        {layout.spendingWaterfalls.map((wf, i) => (
          <WaterfallStream key={wf.id} wf={wf} index={i} />
        ))}

        {/* Layer 6: Outcome pools */}
        {layout.outcomes.map(o => (
          <OutcomePool key={o.id} outcome={o} />
        ))}

        {/* Title watermark */}
        <text
          x={layout.width / 2}
          y={layout.height - 20}
          textAnchor="middle"
          fill="rgba(148,163,184,0.15)"
          fontSize={14}
          fontWeight={700}
          letterSpacing={4}
        >
          rFUNDS BUDGET RIVER
        </text>
      </svg>
    </div>
  )
}
