'use client'

/**
 * FlowPipeline - AI中心 v6 事件流程管線
 * ========================================
 * 7節點水平管線：告警→AI偵測→AI分析→提案生成→等待授權→執行→完成
 * 4種嚴重度對應不同管線樣式：
 *   P0 → Style A: 脈衝光波 (紅 #cc2200)
 *   P1 → Style B: 進度條 (橘 #F59E0B)
 *   P2 → Style C: 卡片步驟 (藍 #4A90D9)
 *   P3 → Style D: 時間軸 (綠 #22C55E)
 * 2026-04-02 Claude Code: 新增 severity prop + 四種管線渲染
 */

export type FlowStage =
  | 'alert'
  | 'detection'
  | 'analysis'
  | 'proposal'
  | 'approval'
  | 'execution'
  | 'resolved'

export type NodeStatus = 'done' | 'active' | 'pending' | 'resolved'

interface FlowNode {
  id: FlowStage
  label: string
}

export interface FlowPipelineProps {
  activeStage: FlowStage
  isResolved?: boolean
  severity?: 'P0' | 'P1' | 'P2' | 'P3'
  tooltips?: Partial<Record<FlowStage, string>>
}

const FLOW_NODES: FlowNode[] = [
  { id: 'alert',     label: '告警' },
  { id: 'detection', label: 'AI偵測' },
  { id: 'analysis',  label: 'AI分析' },
  { id: 'proposal',  label: '提案生成' },
  { id: 'approval',  label: '等待授權' },
  { id: 'execution', label: '執行' },
  { id: 'resolved',  label: '完成' },
]

const SEV_COLOR: Record<string, string> = {
  P0: '#cc2200',
  P1: '#F59E0B',
  P2: '#4A90D9',
  P3: '#22C55E',
}

function getActiveIndex(activeStage: FlowStage): number {
  return FLOW_NODES.findIndex(n => n.id === activeStage)
}

function getNodeStatus(nodeId: FlowStage, activeStage: FlowStage, isResolved: boolean): NodeStatus {
  if (isResolved) return 'resolved'
  const nodeIndex = FLOW_NODES.findIndex(n => n.id === nodeId)
  const activeIndex = getActiveIndex(activeStage)
  if (nodeIndex < activeIndex) return 'done'
  if (nodeIndex === activeIndex) return 'active'
  return 'pending'
}

// ── OpenClaw Icon (取代龍蝦 — Sprint 5R 設計稿批准) ──────────────────────────
// 來源: https://cdn.jsdelivr.net/gh/homarr-labs/dashboard-icons/png/openclaw.png

function OpenClawIcon({ size = 20 }: { size?: number }) {
  return (
    <img
      src="https://cdn.jsdelivr.net/gh/homarr-labs/dashboard-icons/png/openclaw.png"
      alt="OpenClaw"
      width={size}
      height={size}
      style={{ borderRadius: '50%' }}
    />
  )
}

// ── Style A: P0 脈衝光波 ──────────────────────────────────────────────────────

function PipelineStyleA({ activeStage, isResolved }: { activeStage: FlowStage; isResolved: boolean }) {
  const color = isResolved ? '#22C55E' : SEV_COLOR.P0
  const activeIdx = getActiveIndex(activeStage)

  return (
    <div style={{ padding: '4px 10px 8px', overflowX: 'auto' }}>
      <style>{`
        @keyframes pulse-wave {
          0%   { box-shadow: 0 0 0 0 rgba(204,34,0,0.6); }
          70%  { box-shadow: 0 0 0 8px rgba(204,34,0,0); }
          100% { box-shadow: 0 0 0 0 rgba(204,34,0,0); }
        }
        @keyframes flow-light {
          0%   { background-position: -200% 0; }
          100% { background-position: 200% 0; }
        }
        .pipe-a-conn-done {
          background: linear-gradient(90deg, transparent 0%, ${color} 50%, transparent 100%);
          background-size: 200% 100%;
          animation: flow-light 1.4s linear infinite;
        }
      `}</style>
      <div style={{ display: 'flex', alignItems: 'center', gap: 0, minWidth: 'max-content' }}>
        {FLOW_NODES.map((node, idx) => {
          const status = getNodeStatus(node.id, activeStage, isResolved)
          const isActive = status === 'active'
          const isDone = status === 'done' || status === 'resolved'
          const isLast = idx === FLOW_NODES.length - 1

          return (
            <div key={node.id} style={{ display: 'flex', alignItems: 'center' }}>
              <div style={{ display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 2 }}>
                <div style={{ height: 22, display: 'flex', alignItems: 'flex-end', justifyContent: 'center' }}>
                  {isActive && (
                    <div style={{ animation: 'lobster-bob 1.5s ease-in-out infinite' }}>
                      <OpenClawIcon />
                    </div>
                  )}
                </div>
                <div style={{
                  width: 10, height: 10,
                  borderRadius: '50%',
                  background: isDone ? color : isActive ? '#fff' : '#f8f9fc',
                  border: isActive ? `2px solid ${color}` : isDone ? 'none' : '1.5px solid #e0ddd4',
                  animation: isActive ? 'pulse-wave 1.2s ease-out infinite' : 'none',
                  flexShrink: 0,
                }} />
                <span style={{
                  fontSize: 11,
                  color: isActive ? '#141413' : isDone ? color : '#b0ad9f',
                  fontWeight: isActive ? 700 : 400,
                  marginTop: 2, whiteSpace: 'nowrap',
                }}>
                  {node.label}
                </span>
              </div>
              {!isLast && (
                <div
                  className={idx < activeIdx ? 'pipe-a-conn-done' : ''}
                  style={{
                    width: 16, height: 2,
                    background: idx < activeIdx ? undefined : '#e0ddd4',
                    flexShrink: 0,
                    marginBottom: 18,
                  }}
                />
              )}
            </div>
          )
        })}
      </div>
    </div>
  )
}

// ── Style B: P1 進度條 ────────────────────────────────────────────────────────

function PipelineStyleB({ activeStage, isResolved }: { activeStage: FlowStage; isResolved: boolean }) {
  const color = isResolved ? '#22C55E' : SEV_COLOR.P1
  const activeIdx = getActiveIndex(activeStage)
  const totalNodes = FLOW_NODES.length
  const progressPct = isResolved ? 100 : (activeIdx / (totalNodes - 1)) * 100

  return (
    <div style={{ padding: '4px 10px 12px', overflowX: 'auto' }}>
      {/* 進度條軌道 */}
      <div style={{ position: 'relative', height: 54 }}>
        {/* 底部軌道 */}
        <div style={{
          position: 'absolute', bottom: 16, left: 0, right: 0,
          height: 4, background: '#e8e5dc', borderRadius: 2,
        }} />
        {/* 已完成進度 */}
        <div style={{
          position: 'absolute', bottom: 16, left: 0,
          height: 4, background: color, borderRadius: 2,
          width: `${progressPct}%`,
          transition: 'width 0.4s ease',
        }} />
        {/* 節點圓點 */}
        {FLOW_NODES.map((node, idx) => {
          const pct = (idx / (totalNodes - 1)) * 100
          const status = getNodeStatus(node.id, activeStage, isResolved)
          const isActive = status === 'active'
          const isDone = status === 'done' || status === 'resolved'

          return (
            <div
              key={node.id}
              style={{
                position: 'absolute',
                bottom: 0,
                left: `${pct}%`,
                transform: 'translateX(-50%)',
                display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 2,
              }}
            >
              {/* 龍蝦 (active 節點，站在進度條終點上方) */}
              {isActive && (
                <div style={{ animation: 'lobster-bob 1.5s ease-in-out infinite', marginBottom: 2 }}>
                  <OpenClawIcon size={16} />
                </div>
              )}
              {!isActive && <div style={{ height: 20 }} />}
              {/* 圓點 */}
              <div style={{
                width: 8, height: 8, borderRadius: '50%',
                background: isDone ? color : isActive ? '#fff' : '#f8f9fc',
                border: isActive ? `2px solid ${color}` : isDone ? 'none' : '1.5px solid #e0ddd4',
                flexShrink: 0,
              }} />
              {/* 標籤 */}
              <span style={{
                fontSize: 10, color: isActive ? '#141413' : isDone ? color : '#b0ad9f',
                fontWeight: isActive ? 700 : 400,
                whiteSpace: 'nowrap',
              }}>
                {node.label}
              </span>
            </div>
          )
        })}
      </div>
    </div>
  )
}

// ── Style C: P2 卡片步驟 ──────────────────────────────────────────────────────

function PipelineStyleC({ activeStage, isResolved }: { activeStage: FlowStage; isResolved: boolean }) {
  const color = isResolved ? '#22C55E' : SEV_COLOR.P2
  const activeIdx = getActiveIndex(activeStage)

  return (
    <div style={{ padding: '4px 10px 8px', overflowX: 'auto' }}>
      <style>{`
        @keyframes card-glow {
          0%,100% { box-shadow: 0 0 0 0 rgba(74,144,217,0.3); }
          50%      { box-shadow: 0 0 6px 2px rgba(74,144,217,0.3); }
        }
      `}</style>
      <div style={{ display: 'flex', alignItems: 'flex-end', gap: 3, minWidth: 'max-content' }}>
        {FLOW_NODES.map((node, idx) => {
          const status = getNodeStatus(node.id, activeStage, isResolved)
          const isActive = status === 'active'
          const isDone = status === 'done' || status === 'resolved'
          const isLast = idx === FLOW_NODES.length - 1

          return (
            <div key={node.id} style={{ display: 'flex', alignItems: 'flex-end' }}>
              <div style={{ display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 2 }}>
                {/* 龍蝦 */}
                <div style={{ height: 22, display: 'flex', alignItems: 'flex-end', justifyContent: 'center' }}>
                  {isActive && (
                    <div style={{ animation: 'lobster-bob 1.5s ease-in-out infinite' }}>
                      <OpenClawIcon size={16} />
                    </div>
                  )}
                </div>
                {/* 卡片 */}
                <div style={{
                  padding: '3px 6px',
                  background: isDone ? color : isActive ? '#fff' : '#f8f9fc',
                  border: isActive ? `1.5px solid ${color}` : isDone ? 'none' : '1px solid #e0ddd4',
                  borderRadius: 5,
                  animation: isActive ? 'card-glow 1.5s ease-in-out infinite' : 'none',
                  minWidth: 36,
                  textAlign: 'center' as const,
                }}>
                  <span style={{
                    fontSize: 10,
                    color: isDone ? '#fff' : isActive ? color : '#b0ad9f',
                    fontWeight: isActive || isDone ? 700 : 400,
                    whiteSpace: 'nowrap',
                  }}>
                    {node.label}
                  </span>
                </div>
              </div>
              {!isLast && (
                <div style={{
                  width: 8, height: 1.5,
                  background: idx < activeIdx ? color : '#e0ddd4',
                  flexShrink: 0,
                  marginBottom: 11,
                }} />
              )}
            </div>
          )
        })}
      </div>
    </div>
  )
}

// ── Style D: P3 時間軸 ────────────────────────────────────────────────────────

function PipelineStyleD({ activeStage, isResolved }: { activeStage: FlowStage; isResolved: boolean }) {
  const color = isResolved ? '#22C55E' : SEV_COLOR.P3
  const activeIdx = getActiveIndex(activeStage)

  return (
    <div style={{ padding: '4px 10px 8px', overflowX: 'auto' }}>
      <div style={{ display: 'flex', alignItems: 'center', gap: 0, minWidth: 'max-content' }}>
        {FLOW_NODES.map((node, idx) => {
          const status = getNodeStatus(node.id, activeStage, isResolved)
          const isActive = status === 'active'
          const isDone = status === 'done' || status === 'resolved'
          const isLast = idx === FLOW_NODES.length - 1
          const isNextActive = idx === activeIdx - 1

          return (
            <div key={node.id} style={{ display: 'flex', alignItems: 'center' }}>
              <div style={{ display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 2 }}>
                <div style={{ height: 22, display: 'flex', alignItems: 'flex-end', justifyContent: 'center' }}>
                  {isActive && (
                    <div style={{ animation: 'lobster-bob 1.5s ease-in-out infinite' }}>
                      <OpenClawIcon />
                    </div>
                  )}
                </div>
                <div style={{
                  width: 8, height: 8, borderRadius: '50%',
                  background: isDone ? color : isActive ? '#fff' : '#f8f9fc',
                  border: isActive ? `2px solid ${color}` : isDone ? 'none' : '1.5px solid #e0ddd4',
                  flexShrink: 0,
                }} />
                <span style={{
                  fontSize: 11,
                  color: isActive ? '#141413' : isDone ? color : '#b0ad9f',
                  fontWeight: isActive ? 700 : 400,
                  marginTop: 2, whiteSpace: 'nowrap',
                }}>
                  {node.label}
                </span>
              </div>
              {!isLast && (
                <div style={{ marginBottom: 18, flexShrink: 0 }}>
                  {/* Active 前的虛線用 SVG 做流動動畫 */}
                  {isNextActive ? (
                    <svg width="16" height="2" style={{ display: 'block' }}>
                      <line x1="0" y1="1" x2="16" y2="1"
                        stroke={color} strokeWidth="1.5"
                        strokeDasharray="4 3"
                        style={{ animation: 'dash-march 0.6s linear infinite', strokeDashoffset: 0 }}
                      />
                    </svg>
                  ) : (
                    <div style={{
                      width: 16, height: 1.5,
                      background: isDone ? color : '#e0ddd4',
                    }} />
                  )}
                </div>
              )}
            </div>
          )
        })}
      </div>
    </div>
  )
}

// ── Shared Keyframes (injected once at top level to avoid duplication) ────────

const SHARED_KEYFRAMES = `
  @keyframes lobster-bob { 0%,100%{transform:translateY(0)} 50%{transform:translateY(-4px)} }
  @keyframes dash-march { to { stroke-dashoffset: -20; } }
`

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

export function FlowPipeline({ activeStage, isResolved = false, severity = 'P3', tooltips: _tooltips }: FlowPipelineProps) {
  // 2026-04-02 Claude Code: severity → pipeline style mapping
  // P0=StyleA(脈衝光波) P1=StyleB(進度條) P2=StyleC(卡片步驟) P3=StyleD(時間軸)
  // isResolved 傳入各 Style 自行處理顏色，保留嚴重度視覺識別
  const renderedStage = isResolved ? 'resolved' : activeStage
  return (
    <>
      <style>{SHARED_KEYFRAMES}</style>
      <div
        data-testid="incident-flow-pipeline"
        data-flow-stage={renderedStage}
        data-flow-severity={severity}
        data-flow-resolved={isResolved ? 'true' : 'false'}
        aria-label={`incident-flow:${renderedStage}`}
      >
        {severity === 'P0' && <PipelineStyleA activeStage={activeStage} isResolved={isResolved} />}
        {severity === 'P1' && <PipelineStyleB activeStage={activeStage} isResolved={isResolved} />}
        {severity === 'P2' && <PipelineStyleC activeStage={activeStage} isResolved={isResolved} />}
        {(severity === 'P3' || !['P0','P1','P2'].includes(severity)) && <PipelineStyleD activeStage={activeStage} isResolved={isResolved} />}
      </div>
    </>
  )
}

export default FlowPipeline
