import { useMemo, useState } from 'react'
import { signalNodes, signalSequence } from '../data'
import type { Locale, LocalizedText } from '../types'

function t(locale: Locale, text: LocalizedText) {
  return text[locale]
}

function Eyebrow({ children }: { children: string }) {
  return <span className="eyebrow">{children}</span>
}

export function SignalMiniGame({ locale }: { locale: Locale }) {
  const [step, setStep] = useState(0)
  const [wrongId, setWrongId] = useState<string | null>(null)
  const completed = step >= signalSequence.length
  const activeIds = useMemo<Set<string>>(() => new Set(signalSequence.slice(0, step)), [step])
  const currentTip = completed
    ? t(locale, {
        zh: '链路已接通。我们在意的从来不是某一项能力单独突出，而是它们最后能压进同一个项目里。',
        en: 'Signal linked. What matters to us is never one isolated strength, but whether everything can finally compress into one real project.',
      })
    : signalNodes.find((n) => n.id === signalSequence[step])?.note
      ? t(locale, signalNodes.find((n) => n.id === signalSequence[step])!.note)
      : t(locale, {
          zh: '按顺序点亮工作室的四个核心环节。',
          en: 'Light up the studio’s four core links in order.',
        })

  const handleNodeClick = (id: string) => {
    if (completed) return
    if (id === signalSequence[step]) { setStep((v) => v + 1); setWrongId(null); return }
    setWrongId(id)
    window.setTimeout(() => setWrongId(null), 320)
  }

  return (
    <div className="signal-module">
      <div className="signal-copy">
        <Eyebrow>{locale === 'zh' ? 'embedded interaction / signal chain' : 'embedded interaction / signal chain'}</Eyebrow>
        <h3>{locale === 'zh' ? '工作室信号链' : 'Studio Signal Chain'}</h3>
        <p>
          {locale === 'zh'
            ? '这里保留一个轻量小交互。按顺序点亮创意、叙事、视觉、工程四个节点，它们也是止夜工作室当前最重要的四个压缩面。'
            : 'A lightweight interaction stays here. Light up idea, narrative, visual, and engineering in order — the four compressed faces that matter most to the studio right now.'}
        </p>
        <div className="signal-meta">
          <strong>{Math.min(step, signalSequence.length)} / {signalSequence.length}</strong>
          <button type="button" className="ghost-button" onClick={() => setStep(0)}>
            {locale === 'zh' ? '重置链路' : 'Reset Chain'}
          </button>
        </div>
        <p className="signal-tip">{currentTip}</p>
      </div>
      <div className="signal-board">
        <svg className="signal-lines" viewBox="0 0 100 100" preserveAspectRatio="none" aria-hidden="true">
          {signalSequence.slice(0, -1).map((fromId, index) => {
            const toId = signalSequence[index + 1]
            const from = signalNodes.find((n) => n.id === fromId)!
            const to = signalNodes.find((n) => n.id === toId)!
            return (
              <line key={`${fromId}-${toId}`} x1={from.x} y1={from.y} x2={to.x} y2={to.y}
                className={step > index + 1 ? 'signal-line active' : 'signal-line'} />
            )
          })}
        </svg>
        {signalNodes.map((node) => (
          <button key={node.id} type="button"
            className={`signal-node${activeIds.has(node.id) ? ' active' : ''}${wrongId === node.id ? ' wrong' : ''}`}
            style={{ left: `${node.x}%`, top: `${node.y}%` }}
            onClick={() => handleNodeClick(node.id)} aria-label={locale === 'zh' ? `点亮${t(locale, node.label)}` : `Activate ${t(locale, node.label)}`}>
            <span>{t(locale, node.label)}</span>
          </button>
        ))}
        {completed ? <div className="signal-complete">{locale === 'zh' ? '链路完成' : 'link complete'}</div> : null}
      </div>
    </div>
  )
}
