// 识别浮层窗口：深色玻璃、不抢焦点；状态完全由 Rust 事件驱动。
// listening / text 两态 + 错误态文案，规格见 doc/frontend-design.html 5.1/5.2
import { useEffect, useState } from 'react';
import { createRoot } from 'react-dom/client';
import '@dudu/design/styles.css';
import { RecognitionOverlay } from '@dudu/design/components/voice/RecognitionOverlay';
import { listen } from '../shared/tauri';

const ERR_TEXT = {
  QUOTA_EXCEEDED: '今日试用已用完，去购买时长',
  RATE_LIMITED: '操作过于频繁，稍后再试',
  SESSION_LIMIT: '单次最长 3 分钟，松开后可继续',
  ASR_UNAVAILABLE: '识别服务暂不可用，稍后再试',
  NETWORK: '连接中断，松开重试',
  NO_ACCESSIBILITY: '需要辅助功能权限才能上屏，去系统设置开启 dudu',
  UNAUTHORIZED: '登录已失效，去重新登录',
  SESSION_ABORTED: '连接断了，这次没说完，重新说一次',
  AUTH_HEADER: '登录信息有误，去重新登录',
  DEVICE_HEADER: '设备标识有误，重启应用试试',
};

// 未知 code（如 BAD_REQUEST/INTERNAL）且服务端 message（omitempty）缺失时的兜底，
// 保证任何 error 帧都有可见错误态，不会因空串停在「听写中」。
const ERR_FALLBACK = '出错了，稍后再试';
function errText(payload) {
  return ERR_TEXT[payload.code] || payload.message || payload.text || ERR_FALLBACK;
}

function OverlayApp() {
  const [finalText, setFinalText] = useState('');
  const [partialText, setPartialText] = useState('');
  const [error, setError] = useState('');

  useEffect(() => {
    const offs = [];
    listen('hotkey', ({ payload }) => {
      if (payload.state === 'down') { setFinalText(''); setPartialText(''); setError(''); }
    }).then((off) => offs.push(off));
    listen('asr', ({ payload }) => {
      if (payload.type === 'partial') setPartialText(payload.text);
      else if (payload.type === 'final') { setFinalText((f) => f + payload.text); setPartialText(''); }
      else if (payload.type === 'error') setError(errText(payload));
    }).then((off) => offs.push(off));
    return () => offs.forEach((off) => off());
  }, []);

  const hasText = finalText || partialText;
  return (
    <div style={{ padding: 8 }}>
      {error ? (
        <RecognitionOverlay state="text" finalText="" partialText={error} hint="dudu" />
      ) : (
        <RecognitionOverlay
          state={hasText ? 'text' : 'listening'}
          finalText={finalText}
          partialText={partialText}
          hint="松开 ⌘⇧Space 完成输入"
        />
      )}
    </div>
  );
}

createRoot(document.getElementById('root')).render(<OverlayApp />);
