/* voice-mode.jsx — ChatGPT-Advanced-Voice-style fullscreen voice UI.
 * Single mock conversation: AI greets, then 3 user-AI exchange turns.
 * State machine: idle -> speaking -> listening -> thinking -> speaking ... -> done.
 * Mobile-first. Uses Tailwind utility classes for layout.
 */

function ScreenVoice({ scenario, onComplete }) {
  const T = useT();
  const { lang } = useLang();

  // Conversation state
  // turn = 0..3 (3 user turns + final AI summary cue). Greeting is turn -1.
  const [turn, setTurn] = React.useState(-1);
  const [state, setState] = React.useState('idle'); // idle | speaking | listening | thinking | done
  const [caption, setCaption] = React.useState('');
  const timerRef = React.useRef(null);

  // Reset timer helper
  const schedule = (fn, ms) => {
    if (timerRef.current) clearTimeout(timerRef.current);
    timerRef.current = setTimeout(fn, ms);
  };
  React.useEffect(() => () => { if (timerRef.current) clearTimeout(timerRef.current); }, []);

  // Build dialog lines
  const greeting = T({
    th: 'สวัสดีค่ะ ดิฉันเป็น AI พยาบาลคัดกรองนะคะ วันนี้มาด้วยอาการอะไรบ้างคะ?',
    en: 'Hello, I am the AI triage nurse. What brings you in today?',
  });

  // Each turn = user STT phrase, then AI follow-up question (or final line)
  const triage = scenario.triage || [];
  const userLineFor = (t) => window.getSTTPhrase(scenario, t, lang);
  const aiQuestionFor = (t) => {
    if (t < triage.length) return T(triage[t].q);
    // Final wrap-up line after last user reply
    return T({
      th: 'ขอบคุณค่ะ ข้อมูลครบแล้ว กำลังประมวลผลและสรุปแผนกที่เหมาะสมให้นะคะ',
      en: 'Thank you. I have enough information. Let me prepare your summary now.',
    });
  };

  // Kick off greeting on mount
  React.useEffect(() => {
    setState('speaking');
    setCaption(greeting);
    schedule(() => {
      // After greeting, listen for user
      setState('listening');
      setCaption('');
      schedule(() => {
        setCaption(userLineFor(0));
        schedule(() => {
          setState('thinking');
          schedule(() => {
            setState('speaking');
            setCaption(aiQuestionFor(0));
            schedule(advanceFromAi(1), 3200);
          }, 1200);
        }, 1100);
      }, 2500);
    }, 3600);
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [lang, scenario.id]);

  // Returns a function that advances to "listening" for turn `nextTurn`
  function advanceFromAi(nextTurn) {
    return () => {
      if (nextTurn > 3) {
        setState('done');
        setCaption(T({
          th: 'สรุปผลพร้อมแล้ว กดปุ่ม "ดูสรุป" ด้านล่างค่ะ',
          en: 'Your summary is ready. Tap "View summary" below.',
        }));
        return;
      }
      setState('listening');
      setCaption('');
      schedule(() => {
        setCaption(userLineFor(nextTurn));
        schedule(() => {
          setState('thinking');
          schedule(() => {
            setState('speaking');
            setCaption(aiQuestionFor(nextTurn));
            schedule(advanceFromAi(nextTurn + 1), 3200);
          }, 1200);
        }, 1100);
      }, 2500);
      setTurn(nextTurn);
    };
  }

  const statusText = (() => {
    switch (state) {
      case 'speaking':  return T({ th: 'AI กำลังพูด...', en: 'AI is speaking...' });
      case 'listening': return T({ th: 'กำลังฟัง...', en: 'Listening...' });
      case 'thinking':  return T({ th: 'กำลังคิด...', en: 'Thinking...' });
      case 'done':      return T({ th: 'พร้อมสรุปผล', en: 'Ready for summary' });
      default:          return T({ th: 'แตะไมค์เพื่อเริ่ม', en: 'Tap mic to start' });
    }
  })();

  // Restart whole conversation (mic toggle behaviour for demo)
  const restart = () => {
    setTurn(-1);
    setState('speaking');
    setCaption(greeting);
    schedule(() => {
      setState('listening');
      setCaption('');
      schedule(() => {
        setCaption(userLineFor(0));
        schedule(() => {
          setState('thinking');
          schedule(() => {
            setState('speaking');
            setCaption(aiQuestionFor(0));
            schedule(advanceFromAi(1), 3200);
          }, 1200);
        }, 1100);
      }, 2500);
    }, 3600);
  };

  return (
    <div className="relative w-full h-full overflow-hidden flex flex-col"
         style={{
           background: 'radial-gradient(ellipse at 50% 30%, #0E2728 0%, #050C0D 65%, #000 100%)',
           color: '#fff',
         }}>
      {/* Top bar */}
      <div className="flex items-center justify-between px-5 pt-[max(1rem,env(safe-area-inset-top))] pb-3 shrink-0">
        <div className="flex items-center gap-2">
          <img src="assets/mordee-logo.png" alt="MorDee"
               className="h-7"
               style={{ filter: 'brightness(0) invert(1)', opacity: 0.92 }}/>
          <span className="text-sm font-medium tracking-wider opacity-70">VOICE</span>
        </div>
        <LangToggle size="sm" tone="dark"/>
      </div>

      {/* Center — orb + caption */}
      <div className="flex-1 flex flex-col items-center justify-center px-6 gap-8 min-h-0">
        <div className="text-sm font-medium tracking-widest uppercase opacity-70">
          {statusText}
        </div>

        <Orb state={state}/>

        <div className="w-full max-w-[480px] text-center min-h-[88px] flex items-center justify-center">
          <p className="text-lg sm:text-xl leading-relaxed font-medium"
             style={{ color: 'rgba(255,255,255,.92)', textWrap: 'balance' }}>
            {caption}
          </p>
        </div>
      </div>

      {/* Bottom controls */}
      <div className="flex items-center justify-center gap-8 px-6 pt-4 pb-[max(2rem,env(safe-area-inset-bottom))] shrink-0">
        {state === 'done' ? (
          <button
            onClick={onComplete}
            className="rounded-full px-7 h-14 sm:h-16 font-bold text-base sm:text-lg tracking-wide flex items-center gap-3"
            style={{
              background: 'linear-gradient(135deg, #6FC3C4 0%, #4F8A8B 100%)',
              color: '#0F2A2C',
              boxShadow: '0 10px 32px rgba(111,195,196,.35), inset 0 1px 0 rgba(255,255,255,.4)',
              border: 'none', cursor: 'pointer',
            }}>
            <i className="ph-fill ph-clipboard-text text-2xl"></i>
            {T({ th: 'ดูสรุป', en: 'View summary' })}
          </button>
        ) : (
          <button
            onClick={restart}
            aria-label={T({ th: 'สลับไมค์', en: 'Toggle mic' })}
            className="rounded-full w-14 h-14 sm:w-16 sm:h-16 flex items-center justify-center"
            style={{
              background: state === 'listening'
                ? 'linear-gradient(135deg, #6FC3C4, #4F8A8B)'
                : 'rgba(255,255,255,.08)',
              border: '1px solid rgba(255,255,255,.18)',
              color: '#fff', cursor: 'pointer',
              boxShadow: state === 'listening' ? '0 0 24px rgba(111,195,196,.55)' : 'none',
              transition: 'all .25s',
            }}>
            <i className={`ph-fill ${state === 'listening' ? 'ph-microphone' : 'ph-microphone-slash'} text-2xl sm:text-3xl`}></i>
          </button>
        )}

        <button
          onClick={onComplete}
          aria-label={T({ th: 'จบการสนทนา', en: 'End conversation' })}
          className="rounded-full w-14 h-14 sm:w-16 sm:h-16 flex items-center justify-center"
          style={{
            background: 'rgba(251,115,92,.18)',
            border: '1px solid rgba(251,115,92,.45)',
            color: '#FB735C', cursor: 'pointer',
          }}>
          <i className="ph-fill ph-x text-2xl sm:text-3xl"></i>
        </button>
      </div>
    </div>
  );
}

// ─────────────────────────────────────────────────────────────
// Orb — gradient sphere that morphs by state
// ─────────────────────────────────────────────────────────────
function Orb({ state }) {
  const sizeCls = 'w-[60vw] max-w-[320px] aspect-square';
  const animation = (() => {
    switch (state) {
      case 'speaking':  return 'orb-speak-pulse 1.1s ease-in-out infinite';
      case 'listening': return 'orb-listen-pulse 1.6s ease-in-out infinite';
      case 'thinking':  return 'orb-think-rotate 2.4s linear infinite';
      default:          return 'orb-breathe 4.5s ease-in-out infinite';
    }
  })();
  const scaleClassExtra = state === 'thinking' ? 'scale-90' : '';

  return (
    <div className={`relative ${sizeCls} ${scaleClassExtra}`}
         style={{ transition: 'transform .5s ease' }}>
      {/* Outer glow ring(s) — only during speaking/listening */}
      {(state === 'speaking' || state === 'listening') && (
        <>
          <div className="absolute inset-0 rounded-full pointer-events-none"
               style={{
                 background: 'radial-gradient(circle, rgba(111,195,196,.35) 0%, transparent 65%)',
                 animation: 'orb-glow-ring 2s ease-out infinite',
               }}/>
          <div className="absolute inset-0 rounded-full pointer-events-none"
               style={{
                 background: 'radial-gradient(circle, rgba(251,115,92,.22) 0%, transparent 60%)',
                 animation: 'orb-glow-ring 2.6s ease-out .4s infinite',
               }}/>
        </>
      )}

      {/* Conic gradient blurry blob — the heart of the orb */}
      <div className="absolute inset-0 rounded-full"
           style={{
             background: 'conic-gradient(from var(--orb-rot,0deg), #6FC3C4, #FB735C, #2F5252, #6FC3C4)',
             filter: 'blur(28px) saturate(1.4)',
             animation,
             transformOrigin: '50% 50%',
           }}/>

      {/* Inner glossy sphere — radial highlight + soft fill */}
      <div className="absolute inset-[8%] rounded-full pointer-events-none"
           style={{
             background: 'radial-gradient(circle at 32% 28%, rgba(255,255,255,.55) 0%, rgba(255,255,255,.08) 30%, rgba(15,42,44,.0) 60%)',
             mixBlendMode: 'screen',
           }}/>

      {/* Inner darker core for depth */}
      <div className="absolute inset-[18%] rounded-full pointer-events-none"
           style={{
             background: 'radial-gradient(circle at 60% 70%, rgba(15,42,44,.55) 0%, transparent 70%)',
           }}/>
    </div>
  );
}

window.ScreenVoice = ScreenVoice;
