'use client';

import { useState } from 'react';
import { cn } from '@/lib/utils';
import { MD } from './shared';
import type { ScriptSection } from './mock-data';

/** 话术 3 种展示模式 */
export type ScriptViewMode = 'copilot' | 'cards' | 'markdown';

// ──────────────────────────────────────────
// 原文 — Markdown 全文(折叠分段)
// ──────────────────────────────────────────
export function ScriptMarkdown({ sections, streaming = false }: { sections: ScriptSection[]; streaming?: boolean }) {
  // 默认全部展开(客服要一眼看全)。只记录被用户**主动折叠**的段(undefined = 展开)。
  //   关键:流式时段 id 会变(skeleton 的 opening… → 真内容 s0/s1…),用"默认展开"语义
  //   保证新出现的段也展开,不依赖初始 id 集(否则流式中原文是折叠的)。
  const [collapsed, setCollapsed] = useState<Record<string, boolean>>({});
  return (
    <div className="space-y-2">
      {sections.map((sec, idx) => {
        const isOpen = !collapsed[sec.id];
        return (
          <div key={sec.id} className="rounded-md border bg-white overflow-hidden">
            <button
              onClick={() => setCollapsed({ ...collapsed, [sec.id]: !collapsed[sec.id] })}
              className="w-full flex items-center justify-between gap-2 px-3 py-2 text-left hover:bg-slate-50"
            >
              <div className="flex items-center gap-2">
                <span className="w-5 h-5 rounded text-[10.5px] flex items-center justify-center font-semibold bg-brand-50 text-brand-700">
                  {idx + 1}
                </span>
                <span className={cn('text-[13px] font-semibold text-slate-900', streaming && 'shimmer-text')}>
                  {sec.label}
                </span>
              </div>
              <svg
                viewBox="0 0 24 24"
                fill="none"
                stroke="currentColor"
                strokeWidth="2"
                className={cn('w-4 h-4 text-slate-400 transition-transform', isOpen && 'rotate-180')}
              >
                <path d="M6 9l6 6 6-6" />
              </svg>
            </button>
            {isOpen && (
              <div className="px-3 pb-3 pt-1 border-t">
                <MD text={sec.markdown} />
              </div>
            )}
          </div>
        );
      })}
    </div>
  );
}

// ──────────────────────────────────────────
// 卡片 — 步骤化卡片(平铺)
// ──────────────────────────────────────────
export function ScriptStepCards({ sections, streaming = false }: { sections: ScriptSection[]; streaming?: boolean }) {
  return (
    <div className="grid grid-cols-1 md:grid-cols-2 gap-3">
      {sections.map((sec, i) => (
        <div key={sec.id} className="rounded-md border bg-white p-3 flex flex-col">
          <div className="flex items-center justify-between mb-2">
            <div className="flex items-center gap-2">
              <span className="w-6 h-6 rounded-full bg-brand-600 text-white text-[11px] font-semibold flex items-center justify-center">
                {i + 1}
              </span>
              <span className={cn('text-[13px] font-semibold text-slate-900', streaming && 'shimmer-text')}>
                {sec.label}
              </span>
            </div>
          </div>
          <div className="text-[12px] leading-relaxed">
            <MD text={sec.markdown} />
          </div>
        </div>
      ))}
    </div>
  );
}

// ──────────────────────────────────────────
// 伴飞 — 通话伴飞(单段高亮 + 进度条 + 上/下一段)
// ──────────────────────────────────────────
export function ScriptCopilot({ sections, streaming = false }: { sections: ScriptSection[]; streaming?: boolean }) {
  const [active, setActive] = useState(0);
  const cur = sections[active];
  if (!cur) return null;
  return (
    <div className="flex flex-col gap-3">
      {/* 进度条 */}
      <div className="flex items-center gap-1.5 rounded-md bg-slate-50 border p-1.5">
        {sections.map((s, i) => (
          <button
            key={s.id}
            onClick={() => setActive(i)}
            className={cn(
              'flex-1 min-w-0 text-[11px] font-medium px-2 py-1.5 rounded transition-colors flex items-center justify-center gap-1.5',
              i === active
                ? 'bg-brand-600 text-white shadow-sm'
                : i < active
                  ? 'text-brand-700 hover:bg-white'
                  : 'text-slate-500 hover:bg-white',
            )}
          >
            <span
              className={cn(
                'w-4 h-4 flex-none rounded-full flex items-center justify-center text-[9.5px]',
                i === active
                  ? 'bg-white/20 text-white'
                  : i < active
                    ? 'bg-brand-100 text-brand-700'
                    : 'bg-slate-200 text-slate-500',
              )}
            >
              {i < active ? '✓' : i + 1}
            </span>
            <span className="truncate">{s.label}</span>
          </button>
        ))}
      </div>

      {/* 当前段高亮 */}
      <div className="rounded-md border-2 border-brand-200 bg-brand-50/30 p-4 ring-1 ring-brand-100">
        <div className="flex items-center justify-between mb-2">
          <div className="flex items-center gap-2">
            <span className="w-2 h-2 rounded-full bg-brand-500 animate-pulse" />
            <span className="text-[11px] text-brand-700 font-semibold uppercase tracking-wide">当前段</span>
            <span className={cn('text-[14px] font-semibold text-slate-900', streaming && 'shimmer-text')}>
              {cur.label}
            </span>
          </div>
        </div>
        <MD text={cur.markdown} />
        <div className="mt-3 flex items-center justify-between pt-2 border-t border-brand-100">
          <button
            disabled={active === 0}
            onClick={() => setActive(Math.max(0, active - 1))}
            className="text-[12px] text-slate-600 hover:text-slate-900 disabled:text-slate-300 inline-flex items-center gap-1"
          >
            ← 上一段
          </button>
          <span className="text-[11px] text-slate-500 tabular-nums">
            {active + 1} / {sections.length}
          </span>
          <button
            disabled={active === sections.length - 1}
            onClick={() => setActive(Math.min(sections.length - 1, active + 1))}
            className="text-[12px] text-brand-700 font-medium hover:text-brand-900 disabled:text-slate-300 inline-flex items-center gap-1"
          >
            下一段 →
          </button>
        </div>
      </div>
    </div>
  );
}

/** 按模式分发 */
export function ScriptView({
  mode,
  sections,
  streaming = false,
}: {
  mode: ScriptViewMode;
  sections: ScriptSection[];
  streaming?: boolean;
}) {
  if (mode === 'cards') return <ScriptStepCards sections={sections} streaming={streaming} />;
  if (mode === 'markdown') return <ScriptMarkdown sections={sections} streaming={streaming} />;
  return <ScriptCopilot sections={sections} streaming={streaming} />;
}
