'use client';

import { type RefObject } from 'react';
import { cn } from '@/lib/utils';
import { AudioVisualizer } from './audio-visualizer';
import type { CoachState } from './types';

/** 逐级虚化:depth 0=当前句(清晰醒目),1=前一句,2=前前一句(越上越淡越糊),更老的不展示 */
const DEPTH_STYLE = [
  'text-[15.5px] font-semibold text-slate-900 leading-relaxed [text-shadow:0_1px_10px_rgba(255,255,255,0.95)]',
  'text-[13.5px] text-slate-500 leading-snug opacity-85 line-clamp-2',
  'text-[12.5px] text-slate-400 leading-snug blur-[0.6px] opacity-60 line-clamp-1',
];

/**
 * 字幕式教练浮层 — 锚在麦克风钮正上方,居中。
 * 自下而上:波形 → 当前句(醒目滑入)→ 前一句 → 前前一句(逐级虚化)。
 */
export function CoachOverlay({
  state,
  analyserRef,
}: {
  state: CoachState;
  analyserRef: RefObject<AnalyserNode | null>;
}) {
  const active = state.status === 'active';

  // 组装"最新在前"的栈:[当前, 前一, 前前](最多 3 条)
  const stack: { text: string; key: string }[] = [];
  let placeholder = '';

  if (state.status === 'connecting') {
    placeholder = '连接中…';
  } else if (state.status === 'error') {
    placeholder = state.message;
  } else if (active) {
    const lines = state.lines;
    const streaming = state.streaming.trim();
    if (streaming) {
      stack.push({ text: streaming, key: `s${lines.length}` });
      for (let d = 1; d <= 2; d++) {
        const t = lines[lines.length - d];
        if (t) stack.push({ text: t, key: `l${lines.length - d}` });
      }
    } else {
      for (let d = 0; d <= 2; d++) {
        const t = lines[lines.length - 1 - d];
        if (t) stack.push({ text: t, key: `l${lines.length - 1 - d}` });
      }
    }
    if (stack.length === 0) placeholder = '正在收听,患者开口后给提示…';
  }

  return (
    <div className="absolute bottom-[4.75rem] left-1/2 -translate-x-1/2 z-20 w-[min(94%,620px)] flex flex-col items-center gap-2.5 pointer-events-none">
      {/* 字幕栈(渲染时反转:越老越上) */}
      <div className="w-full flex flex-col items-center justify-end gap-2 px-6 min-h-[5rem]">
        {stack.length === 0 ? (
          <p className="text-[12.5px] text-slate-400">{placeholder}</p>
        ) : (
          [...stack].reverse().map((item, i) => {
            const depth = stack.length - 1 - i; // 反转后:末项=当前句 depth 0
            return (
              <p
                key={item.key}
                className={cn(
                  'max-w-full text-center transition-all duration-300',
                  DEPTH_STYLE[depth],
                  depth === 0 && 'animate-lyricIn',
                )}
              >
                {item.text}
              </p>
            );
          })
        )}
      </div>

      {/* 波形:正下方,随真实麦克风电平起伏 */}
      <AudioVisualizer analyserRef={analyserRef} active={active} />
    </div>
  );
}
