'use client'

/**
 * ServiceNode — React Flow 自定義服務節點
 * ========================================
 * Sprint 5 Phase 2: 顯示真實服務狀態
 *
 * 設計規範:
 *   - 圓角 8px, 0.5px 邊框
 *   - 狀態燈 + 服務名稱 + 端口
 *   - DM Mono 字體
 *   - React.memo + areEqual 防止無關 re-render
 *
 * 建立時間: 2026-04-08 (台北時區)
 */

import { memo } from 'react'
import { Handle, Position, type NodeProps } from '@xyflow/react'

// 狀態 → 色彩
const STATUS_COLOR: Record<string, string> = {
  up: '#22C55E',
  healthy: '#22C55E',
  down: '#cc2200',
  degraded: '#F59E0B',
  warning: '#F59E0B',
  thinking: '#4A90D9',
  syncing: '#4A90D9',
}

function ServiceNodeInner({ data }: NodeProps) {
  const d = data as Record<string, any>
  const color = STATUS_COLOR[d.status] || '#b0ad9f'
  const isDown = d.status === 'down'
  const port = d.port ? `:${d.port}` : ''

  return (
    <div
      style={{
        background: '#fff',
        border: `0.5px solid ${isDown ? '#cc2200' : '#e0ddd4'}`,
        borderRadius: 8,
        padding: '5px 10px',
        minWidth: 110,
        fontFamily: "'DM Mono', monospace",
        fontSize: 11,
        boxShadow: '0 1px 2px rgba(0,0,0,0.04)',
        transition: 'border-color 0.2s',
      }}
    >
      <Handle type="target" position={Position.Left} style={{ width: 4, height: 4, background: '#e0ddd4' }} />

      <div style={{ display: 'flex', alignItems: 'center', gap: 5 }}>
        <span style={{ width: 5, height: 5, borderRadius: '50%', background: color, flexShrink: 0 }} />
        <span style={{ fontWeight: 600, fontSize: 11, color: '#141413', whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>
          {d.name}
        </span>
      </div>

      {(port || d.latency) && (
        <div style={{ fontSize: 9, color: '#87867f', marginTop: 2, fontFamily: "'JetBrains Mono', monospace" }}>
          {d.hostIp}{port}
          {d.latency != null && ` · ${d.latency}ms`}
        </div>
      )}

      {d.error && (
        <div style={{ fontSize: 9, color: '#cc2200', marginTop: 2 }}>
          {String(d.error).slice(0, 30)}
        </div>
      )}

      <Handle type="source" position={Position.Right} style={{ width: 4, height: 4, background: '#e0ddd4' }} />
    </div>
  )
}

// memo: 只在 status/latency/error 變化時 re-render
export const ServiceNode = memo(ServiceNodeInner, (prev, next) => {
  const p = prev.data as Record<string, any>
  const n = next.data as Record<string, any>
  return p.status === n.status && p.latency === n.latency && p.error === n.error
})
