// feedback.jsx — Fire Lingo Face-to-Face post-session feedback survey
// Shown to the member (in their language) after the employee taps "Finish serving member".
// Employee can also fill it in if the member has already left — segmented at the bottom.

const FEEDBACK_COPY = {
  // English fallback first; each lang overrides what it can.
  en: {
    title:   'Quick feedback',
    subtitle:'Your answers help us serve you better.',
    q1:      'Was it easy to talk with us using this tablet?',
    q2:      'Would you use this tablet again?',
    q3:      'How was your visit at {bank} today?',
    q4:      'Tell us about your experience with the tablet.',
    q4Hint:  'Hold the circle and speak — we\u2019ll capture and translate it.',
    q4Held:  'Listening…',
    role:    'Are you',
    member:  'A member',
    employee:'An employee',
    submit:  'Submit feedback',
    skip:    'Skip',
    no:      'No',
    yes:     'Yes',
    upset:   'Upset',
    sad:     'Sad',
    neutral: 'Okay',
    happy:   'Happy',
    superHappy: 'Great',
  },
  es: {
    title:   'Comentarios rápidos',
    subtitle:'Sus respuestas nos ayudan a atenderle mejor.',
    q1:      '¿Fue fácil comunicarse usando esta tableta?',
    q2:      '¿La usaría otra vez?',
    q3:      '¿Cómo fue su experiencia en {bank} hoy?',
    q4:      'Cuéntenos sobre su experiencia con la tableta.',
    q4Hint:  'Mantenga presionado el círculo y hable — lo capturamos y traducimos.',
    q4Held:  'Escuchando…',
    role:    'Usted es',
    member:  'Un miembro',
    employee:'Un empleado',
    submit:  'Enviar',
    skip:    'Omitir',
    no:      'No',
    yes:     'Sí',
    upset:   'Muy mal',
    sad:     'Mal',
    neutral: 'Regular',
    happy:   'Bien',
    superHappy: 'Excelente',
  },
  zh: {
    title: '快速反馈', subtitle: '您的回答能帮助我们更好地服务您。',
    q1: '使用这台平板与我们交流是否方便?',
    q2: '您愿意再次使用吗?',
    q3: '您今天在{bank}的体验如何?',
    q4: '请告诉我们您使用平板的体验。',
    q4Hint: '按住圆圈说话 — 我们会录音并翻译。',
    q4Held: '正在聆听…',
    role: '您是', member: '成员', employee: '员工',
    submit: '提交', skip: '跳过',
    no: '否', yes: '是',
    upset: '很糟', sad: '不好', neutral: '一般', happy: '好', superHappy: '非常好',
  },
  vi: {
    title: 'Phản hồi nhanh', subtitle: 'Câu trả lời của bạn giúp chúng tôi phục vụ tốt hơn.',
    q1: 'Có dễ giao tiếp với máy tính bảng này không?',
    q2: 'Bạn có muốn dùng lại không?',
    q3: 'Trải nghiệm của bạn tại {bank} hôm nay thế nào?',
    q4: 'Hãy cho chúng tôi biết trải nghiệm của bạn với máy tính bảng.',
    q4Hint: 'Giữ vòng tròn và nói — chúng tôi sẽ ghi và dịch.',
    q4Held: 'Đang nghe…',
    role: 'Bạn là', member: 'Thành viên', employee: 'Nhân viên',
    submit: 'Gửi', skip: 'Bỏ qua',
    no: 'Không', yes: 'Có',
    upset: 'Rất tệ', sad: 'Tệ', neutral: 'Bình thường', happy: 'Tốt', superHappy: 'Rất tốt',
  },
  ko: {
    title: '간단한 피드백', subtitle: '귀하의 답변이 더 나은 서비스를 만듭니다.',
    q1: '이 태블릿으로 의사소통이 쉬웠나요?',
    q2: '다시 사용하시겠어요?',
    q3: '오늘 {bank} 방문은 어떠셨나요?',
    q4: '태블릿 사용 경험을 알려주세요.',
    q4Hint: '원을 누른 채로 말씀해 주세요 — 녹음해 번역합니다.',
    q4Held: '듣는 중…',
    role: '귀하는', member: '회원', employee: '직원',
    submit: '제출', skip: '건너뛰기',
    no: '아니요', yes: '네',
    upset: '매우 나쁨', sad: '나쁨', neutral: '보통', happy: '좋음', superHappy: '매우 좋음',
  },
  ht: {
    title: 'Fidbak rapid', subtitle: 'Repons ou ede nou sèvi w pi byen.',
    q1: 'Èske li te fasil pou kominike avèk tablèt sa a?',
    q2: 'Èske w ap itilize li ankò?',
    q3: 'Kijan eksperyans ou nan {bank} jodi a?',
    q4: 'Di nou eksperyans ou avèk tablèt la.',
    q4Hint: 'Kenbe sèk la peze epi pale — n ap anrejistre l e tradui l.',
    q4Held: 'N ap koute…',
    role: 'Èske w se', member: 'Yon manm', employee: 'Yon anplwaye',
    submit: 'Voye', skip: 'Sote',
    no: 'Non', yes: 'Wi',
    upset: 'Trè move', sad: 'Move', neutral: 'Konsa konsa', happy: 'Byen', superHappy: 'Trè byen',
  },
  ar: {
    title: 'ملاحظات سريعة', subtitle: 'إجاباتك تساعدنا على خدمتك بشكل أفضل.',
    q1: 'هل كان من السهل التواصل عبر هذا الجهاز؟',
    q2: 'هل ستستخدمه مرة أخرى؟',
    q3: 'كيف كانت زيارتك إلى {bank} اليوم؟',
    q4: 'أخبرنا عن تجربتك مع الجهاز.',
    q4Hint: 'اضغط على الدائرة مع الاستمرار وتحدث — سنسجّل ونترجم.',
    q4Held: 'نستمع الآن…',
    role: 'أنت', member: 'عميل', employee: 'موظف',
    submit: 'إرسال', skip: 'تخطّي',
    no: 'لا', yes: 'نعم',
    upset: 'سيئ جداً', sad: 'سيئ', neutral: 'متوسط', happy: 'جيد', superHappy: 'ممتاز',
  },
  fr: {
    title: 'Avis rapide', subtitle: 'Vos réponses nous aident à mieux vous servir.',
    q1: 'Avez-vous communiqué facilement avec cette tablette ?',
    q2: 'L\u2019utiliseriez-vous à nouveau ?',
    q3: 'Comment s\u2019est passée votre visite à {bank} aujourd\u2019hui ?',
    q4: 'Parlez-nous de votre expérience avec la tablette.',
    q4Hint: 'Maintenez le cercle et parlez — nous enregistrons et traduisons.',
    q4Held: 'Écoute…',
    role: 'Vous êtes', member: 'Un membre', employee: 'Un employé',
    submit: 'Envoyer', skip: 'Passer',
    no: 'Non', yes: 'Oui',
    upset: 'Très mauvais', sad: 'Mauvais', neutral: 'Correct', happy: 'Bien', superHappy: 'Très bien',
  },
  pt: {
    title: 'Comentário rápido', subtitle: 'As suas respostas ajudam-nos a servi-lo melhor.',
    q1: 'Foi fácil comunicar usando este tablet?',
    q2: 'Voltaria a usá-lo?',
    q3: 'Como foi a sua visita a {bank} hoje?',
    q4: 'Conte-nos a sua experiência com o tablet.',
    q4Hint: 'Mantenha o círculo premido e fale — vamos gravar e traduzir.',
    q4Held: 'A ouvir…',
    role: 'Você é', member: 'Um membro', employee: 'Um funcionário',
    submit: 'Enviar', skip: 'Saltar',
    no: 'Não', yes: 'Sim',
    upset: 'Muito mau', sad: 'Mau', neutral: 'Razoável', happy: 'Bom', superHappy: 'Excelente',
  },
  ru: {
    title: 'Быстрый отзыв', subtitle: 'Ваши ответы помогут нам улучшить обслуживание.',
    q1: 'Было ли удобно общаться через этот планшет?',
    q2: 'Воспользуетесь ли вы им снова?',
    q3: 'Как прошёл ваш визит в {bank} сегодня?',
    q4: 'Расскажите о вашем опыте с планшетом.',
    q4Hint: 'Удерживайте круг и говорите — мы запишем и переведём.',
    q4Held: 'Слушаю…',
    role: 'Вы', member: 'Клиент', employee: 'Сотрудник',
    submit: 'Отправить', skip: 'Пропустить',
    no: 'Нет', yes: 'Да',
    upset: 'Очень плохо', sad: 'Плохо', neutral: 'Нормально', happy: 'Хорошо', superHappy: 'Отлично',
  },
  hi: {
    title: 'त्वरित प्रतिक्रिया', subtitle: 'आपके उत्तर हमें बेहतर सेवा देने में मदद करते हैं।',
    q1: 'क्या इस टैबलेट से बात करना आसान था?',
    q2: 'क्या आप इसे दोबारा उपयोग करेंगे?',
    q3: 'आज {bank} में आपका अनुभव कैसा रहा?',
    q4: 'टैबलेट के साथ अपना अनुभव बताएँ।',
    q4Hint: 'गोले को दबाकर बोलें — हम रिकॉर्ड करके अनुवाद करेंगे।',
    q4Held: 'सुन रहे हैं…',
    role: 'आप हैं', member: 'सदस्य', employee: 'कर्मचारी',
    submit: 'भेजें', skip: 'छोड़ें',
    no: 'नहीं', yes: 'हाँ',
    upset: 'बहुत खराब', sad: 'खराब', neutral: 'ठीक', happy: 'अच्छा', superHappy: 'बहुत अच्छा',
  },
  tl: {
    title: 'Mabilis na puna', subtitle: 'Tutulungan kaming magbigay ng mas mahusay na serbisyo.',
    q1: 'Madali bang makipag-usap gamit ang tablet na ito?',
    q2: 'Gagamitin mo ba ulit ito?',
    q3: 'Kumusta ang pagbisita mo sa {bank} ngayon?',
    q4: 'Sabihin sa amin ang karanasan mo sa tablet.',
    q4Hint: 'Pindutin at hawakan ang bilog at magsalita — irerekord at isasalin namin.',
    q4Held: 'Nakikinig…',
    role: 'Ikaw ay', member: 'Isang miyembro', employee: 'Isang empleyado',
    submit: 'Ipadala', skip: 'Laktawan',
    no: 'Hindi', yes: 'Oo',
    upset: 'Napakasama', sad: 'Masama', neutral: 'Sakto', happy: 'Maganda', superHappy: 'Napakaganda',
  },
  sw: {
    title: 'Maoni ya haraka', subtitle: 'Majibu yako yanatusaidia kukuhudumia vizuri zaidi.',
    q1: 'Je, ilikuwa rahisi kuzungumza nasi kwa kutumia kibao hiki?',
    q2: 'Je, utakitumia tena?',
    q3: 'Ulipata uzoefu gani {bank} leo?',
    q4: 'Tuambie kuhusu uzoefu wako na kibao.',
    q4Hint: 'Bonyeza mduara na uzungumze — tutarekodi na kutafsiri.',
    q4Held: 'Tunasikiliza…',
    role: 'Wewe ni', member: 'Mwanachama', employee: 'Mfanyakazi',
    submit: 'Wasilisha', skip: 'Ruka',
    no: 'Hapana', yes: 'Ndio',
    upset: 'Mbaya sana', sad: 'Mbaya', neutral: 'Wastani', happy: 'Vizuri', superHappy: 'Vizuri sana',
  },
};

const BANK_NAME = 'Eastpoint';

function getCopy(code) {
  return { ...FEEDBACK_COPY.en, ...(FEEDBACK_COPY[code] || {}) };
}

// ──────────────────────────────────────────────────────────────────────────
// Face icons — single SVG, expressions vary by mood (5-step scale)
// ──────────────────────────────────────────────────────────────────────────

function FaceIcon({ mood, size = 56 }) {
  // mood: 'upset' (1) | 'sad' (2) | 'neutral' (3) | 'happy' (4) | 'super' (5) | 'no' | 'yes'
  // 'no' aliases 'sad', 'yes' aliases 'super'.
  const m = mood === 'no' ? 'sad' : mood === 'yes' ? 'super' : mood;

  // Eye paths
  const eyes = m === 'upset' ? <>
    <path d="M22 36 l8 -3"  strokeWidth="3.5" />
    <path d="M50 33 l8  3"  strokeWidth="3.5" />
  </> : m === 'super' ? <>
    {/* Squint-happy eyes (upturned arcs) */}
    <path d="M19 32 q5 -6 11 0" strokeWidth="3.5" fill="none" />
    <path d="M42 32 q5 -6 11 0" strokeWidth="3.5" fill="none" />
  </> : <>
    <circle cx="24" cy="32" r="3.2" fill="currentColor" stroke="none" />
    <circle cx="48" cy="32" r="3.2" fill="currentColor" stroke="none" />
  </>;

  // Mouth paths
  const mouth =
    m === 'upset'   ? <path d="M22 52 q14 -14 28 0" strokeWidth="3.8" fill="none" />          :
    m === 'sad'     ? <path d="M24 50 q12 -8 24 0"  strokeWidth="3.6" fill="none" />          :
    m === 'neutral' ? <path d="M24 50 H48"          strokeWidth="3.6" fill="none" />          :
    m === 'happy'   ? <path d="M24 47 q12 8 24 0"   strokeWidth="3.6" fill="none" />          :
    /* super */       <path d="M22 46 q14 14 28 0 z" strokeWidth="3.4" fill="currentColor" stroke="currentColor" strokeLinejoin="round"/>;

  // Background tint per mood
  const bg = m === 'upset'   ? '#9d2a2a' :
             m === 'sad'     ? '#c46438' :
             m === 'neutral' ? '#c39632' :
             m === 'happy'   ? '#5b9c5e' :
             /* super */       '#2d8a55';

  return (
    <svg width={size} height={size} viewBox="0 0 72 72"
      stroke="#fff" strokeLinecap="round" strokeLinejoin="round">
      <circle cx="36" cy="36" r="32" fill={bg} stroke="none" />
      {eyes}
      {mouth}
    </svg>
  );
}

// ──────────────────────────────────────────────────────────────────────────
// Question block
// ──────────────────────────────────────────────────────────────────────────

function FeedbackQuestion({ number, native, english, children, fonts }) {
  return (
    <div style={{ marginTop: 0 }}>
      <div style={{ display: 'flex', alignItems: 'baseline', gap: 12, marginBottom: 10 }}>
        <div style={{
          flexShrink: 0,
          fontFamily: 'var(--font-display)', fontSize: 14, fontWeight: 700,
          width: 26, height: 26, borderRadius: 999,
          background: 'var(--td-blue-50)', color: 'var(--td-blue-600)',
          display: 'flex', alignItems: 'center', justifyContent: 'center',
          letterSpacing: 0,
        }}>{number}</div>
        <div>
          <div style={{
            fontFamily: fonts.native, fontSize: 18, fontWeight: 700,
            color: 'var(--td-navy)', lineHeight: 1.3,
            letterSpacing: fonts.cjk ? 0 : '-0.01em',
          }}>{native}</div>
          {english && english !== native && (
            <div style={{
              fontFamily: 'var(--font-sans)', fontSize: 12, fontWeight: 500,
              color: 'var(--fg3)', lineHeight: 1.3, marginTop: 2,
            }}>{english}</div>
          )}
        </div>
      </div>
      <div>{children}</div>
    </div>
  );
}

// ──────────────────────────────────────────────────────────────────────────
// FACE BUTTON — wraps FaceIcon with selection state and label
// ──────────────────────────────────────────────────────────────────────────

function FaceButton({ mood, label, selected, onClick, size = 64 }) {
  return (
    <button
      onClick={onClick}
      style={{
        display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 6,
        padding: 8,
        background: 'transparent', border: 'none',
        cursor: 'pointer',
        WebkitTapHighlightColor: 'transparent',
      }}>
      <div style={{
        padding: 4, borderRadius: 999,
        background: selected ? 'var(--td-blue)' : 'transparent',
        boxShadow: selected ? '0 0 0 4px rgba(70,137,200,0.18)' : 'none',
        transition: 'all 160ms var(--ease-out)',
        transform: selected ? 'scale(1.04)' : 'scale(1)',
      }}>
        <FaceIcon mood={mood} size={size} />
      </div>
      <div style={{
        fontFamily: 'var(--font-sans)', fontSize: 11, fontWeight: 600,
        color: selected ? 'var(--td-blue-600)' : 'var(--fg3)',
        textTransform: 'uppercase', letterSpacing: '0.06em',
      }}>
        {label}
      </div>
    </button>
  );
}

// ──────────────────────────────────────────────────────────────────────────
// MAIN
// ──────────────────────────────────────────────────────────────────────────

function FeedbackScreen({ language, bankName, brand, onSubmit, onSkip }) {
  const lang = language || LANGUAGES[0];
  const rtl = lang.script === 'rtl';
  const BANK = bankName || BANK_NAME;
  const t = getCopy(lang.code);

  const fonts = {
    native:
      lang.script === 'cjk' ? '"Noto Sans SC", "Noto Sans KR", system-ui' :
      lang.script === 'devanagari' ? '"Noto Sans Devanagari", var(--font-display)' :
      lang.script === 'rtl' ? '"Noto Naskh Arabic", var(--font-display)' :
      'var(--font-display)',
    cjk: lang.script === 'cjk',
  };

  const [q1, setQ1] = React.useState(null);
  const [q2, setQ2] = React.useState(null);
  const [q3, setQ3] = React.useState(null);
  const [voiceState, setVoiceState] = React.useState('idle'); // 'idle' | 'recording' | 'recorded'
  const [voiceLevel, setVoiceLevel] = React.useState(0);
  const [voiceDuration, setVoiceDuration] = React.useState(0);
  const [role, setRole] = React.useState('member');

  // Voice level animation while recording
  React.useEffect(() => {
    if (voiceState !== 'recording') return;
    const start = performance.now();
    let raf;
    let last = start;
    const tick = (now) => {
      const dt = now - last; last = now;
      setVoiceDuration((now - start) / 1000);
      setVoiceLevel(l => {
        const target = 0.55 + 0.35 * Math.sin(now / 230) + (Math.random() - 0.5) * 0.4;
        return Math.max(0.18, Math.min(1, l + (target - l) * (dt / 90)));
      });
      raf = requestAnimationFrame(tick);
    };
    raf = requestAnimationFrame(tick);
    return () => cancelAnimationFrame(raf);
  }, [voiceState]);

  const startVoice = (e) => {
    e.preventDefault();
    if (voiceState === 'idle' || voiceState === 'recorded') {
      setVoiceState('recording');
      setVoiceDuration(0);
    }
  };
  const endVoice = (e) => {
    e.preventDefault();
    if (voiceState === 'recording') {
      setVoiceState(voiceDuration > 0.4 ? 'recorded' : 'idle');
    }
  };
  const clearVoice = () => { setVoiceState('idle'); setVoiceDuration(0); };

  const submit = () => {
    if (onSubmit) onSubmit({
      q1, q2, q3,
      voice: voiceState === 'recorded' ? { duration: voiceDuration } : null,
      role,
    });
  };

  return (
    <div style={{
      width: '100%', height: '100%',
      background: 'var(--td-slate-50)',
      display: 'flex', flexDirection: 'column',
      direction: rtl ? 'rtl' : 'ltr',
      position: 'relative',
    }}>
      {/* Header strip */}
      <div style={{
        flexShrink: 0,
        padding: '20px 36px 18px',
        background: 'linear-gradient(180deg, #fff 0%, #fff 100%)',
        borderBottom: '1px solid var(--border)',
        display: 'flex', alignItems: 'center', gap: 16,
      }}>
        {brand && brand.useDefaultMark === false ? (
          <div style={{
            height: 42,
            width: brand.logoAspect === 'wide' ? 'auto' : 42,
            minWidth: brand.logoAspect === 'wide' ? 110 : 42,
            flexShrink: 0,
            borderRadius: 'var(--radius-md)',
            background: 'var(--td-navy)',
            display: 'flex', alignItems: 'center', justifyContent: 'center',
            padding: brand.logoAspect === 'wide' ? '8px 14px' : 6,
            boxShadow: 'var(--shadow-xs)',
          }}>
            <img src={brand.logoWhite} alt={brand.name} style={{
              height: '100%', width: 'auto', maxWidth: '100%', objectFit: 'contain',
            }} />
          </div>
        ) : (
          <BrandMark size={42} tone="light" />
        )}
        <div style={{ flex: 1, minWidth: 0 }}>
          <div style={{
            fontFamily: fonts.native, fontSize: 22, fontWeight: 800,
            color: 'var(--td-navy)', letterSpacing: fonts.cjk ? 0 : '-0.02em', lineHeight: 1.1,
          }}>{t.title}</div>
          <div style={{
            fontFamily: 'var(--font-sans)', fontSize: 12,
            color: 'var(--fg3)', marginTop: 3,
          }}>{t.subtitle} · {language?.english}</div>
        </div>
        <button onClick={onSkip} style={{
          padding: '8px 14px', background: 'transparent',
          border: '1px solid var(--border)', borderRadius: 'var(--radius-pill)',
          fontFamily: 'var(--font-sans)', fontSize: 12, fontWeight: 600,
          color: 'var(--fg2)', cursor: 'pointer',
          letterSpacing: '0.06em', textTransform: 'uppercase',
        }}>{t.skip} ✕</button>
      </div>

      {/* Body — two columns */}
      <div style={{
        flex: 1, minHeight: 0,
        display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 36,
        padding: '22px 36px 18px',
        overflow: 'auto',
      }}>
        {/* Left column — Q1, Q2, Q3 */}
        <div style={{ display: 'flex', flexDirection: 'column', gap: 22 }}>
          <FeedbackQuestion number="1" native={t.q1} english={FEEDBACK_COPY.en.q1} fonts={fonts}>
            <div style={{ display: 'flex', gap: 18, justifyContent: 'flex-start' }}>
              <FaceButton mood="no"  label={t.no}  selected={q1 === 'no'}  onClick={() => setQ1('no')}  size={68} />
              <FaceButton mood="yes" label={t.yes} selected={q1 === 'yes'} onClick={() => setQ1('yes')} size={68} />
            </div>
          </FeedbackQuestion>

          <FeedbackQuestion number="2" native={t.q2} english={FEEDBACK_COPY.en.q2} fonts={fonts}>
            <div style={{ display: 'flex', gap: 18, justifyContent: 'flex-start' }}>
              <FaceButton mood="no"  label={t.no}  selected={q2 === 'no'}  onClick={() => setQ2('no')}  size={68} />
              <FaceButton mood="yes" label={t.yes} selected={q2 === 'yes'} onClick={() => setQ2('yes')} size={68} />
            </div>
          </FeedbackQuestion>

          <FeedbackQuestion
            number="3"
            native={t.q3.replace('{bank}', BANK)}
            english={FEEDBACK_COPY.en.q3.replace('{bank}', BANK)}
            fonts={fonts}>
            <div style={{ display: 'flex', gap: 6, justifyContent: 'flex-start', flexWrap: 'wrap' }}>
              {[
                { m: 'upset',   l: t.upset      },
                { m: 'sad',     l: t.sad        },
                { m: 'neutral', l: t.neutral    },
                { m: 'happy',   l: t.happy      },
                { m: 'super',   l: t.superHappy },
              ].map(opt => (
                <FaceButton key={opt.m} mood={opt.m} label={opt.l}
                  selected={q3 === opt.m} onClick={() => setQ3(opt.m)} size={56} />
              ))}
            </div>
          </FeedbackQuestion>
        </div>

        {/* Right column — Q4 (voice) + Q5 (role) */}
        <div style={{ display: 'flex', flexDirection: 'column', gap: 22 }}>
          <FeedbackQuestion number="4" native={t.q4} english={FEEDBACK_COPY.en.q4} fonts={fonts}>
            <VoicePrompt
              state={voiceState}
              level={voiceLevel}
              duration={voiceDuration}
              hint={t.q4Hint}
              held={t.q4Held}
              onPointerDown={startVoice}
              onPointerUp={endVoice}
              onPointerLeave={endVoice}
              onPointerCancel={endVoice}
              onClear={clearVoice}
              fonts={fonts}
            />
          </FeedbackQuestion>

          <FeedbackQuestion number="5" native={t.role} english={FEEDBACK_COPY.en.role} fonts={fonts}>
            <RoleToggle
              value={role}
              onChange={setRole}
              memberLabel={t.member}
              employeeLabel={t.employee}
              fonts={fonts}
            />
          </FeedbackQuestion>
        </div>
      </div>

      {/* Footer — submit */}
      <div style={{
        flexShrink: 0,
        padding: '14px 36px 18px',
        background: '#fff',
        borderTop: '1px solid var(--border)',
        display: 'flex', justifyContent: 'flex-end', gap: 12,
      }}>
        <button
          onClick={submit}
          style={{
            minHeight: 56, padding: '0 36px',
            background: 'linear-gradient(180deg, var(--td-blue) 0%, var(--td-blue-600) 100%)',
            color: '#fff', border: 'none', borderRadius: 'var(--radius-md)',
            fontFamily: 'var(--font-display)', fontSize: 18, fontWeight: 800,
            letterSpacing: '-0.01em',
            cursor: 'pointer',
            display: 'inline-flex', alignItems: 'center', gap: 10,
            boxShadow: '0 8px 20px rgba(37,100,152,0.35)',
            WebkitTapHighlightColor: 'transparent',
          }}>
          {t.submit}
          <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.2" strokeLinecap="round" strokeLinejoin="round">
            <path d="M5 12h14M13 5l7 7-7 7"/>
          </svg>
        </button>
      </div>
    </div>
  );
}

// ──────────────────────────────────────────────────────────────────────────
// Voice prompt — Fire Lingo circle (tap and hold)
// ──────────────────────────────────────────────────────────────────────────

function VoicePrompt({ state, level, duration, hint, held, onPointerDown, onPointerUp, onPointerLeave, onPointerCancel, onClear, fonts }) {
  const recording = state === 'recording';
  const recorded  = state === 'recorded';

  return (
    <div style={{
      display: 'flex', alignItems: 'center', gap: 18,
      padding: 16,
      background: '#fff', border: '1px solid var(--border)',
      borderRadius: 'var(--radius-lg)',
    }}>
      <div style={{ position: 'relative', width: 88, height: 88, flexShrink: 0 }}>
        {recording && (
          <div style={{
            position: 'absolute', inset: 0, borderRadius: 9999,
            background: 'radial-gradient(circle, color-mix(in srgb, var(--td-orange) 35%, transparent) 45%, color-mix(in srgb, var(--td-orange) 0%, transparent) 60%)',
            transform: `scale(${1 + level * 0.12})`,
            transition: 'transform 120ms var(--ease-out)',
            pointerEvents: 'none',
          }} />
        )}
        <button
          onPointerDown={onPointerDown}
          onPointerUp={onPointerUp}
          onPointerLeave={onPointerLeave}
          onPointerCancel={onPointerCancel}
          style={{
            position: 'absolute', inset: 0, borderRadius: 9999,
            border: 'none', cursor: 'pointer',
            background: recording
              ? 'radial-gradient(circle at 30% 30%, var(--td-orange) 0%, var(--td-orange) 60%, color-mix(in srgb, var(--td-orange) 65%, #000) 100%)'
              : recorded
              ? 'radial-gradient(circle at 30% 30%, #6a9d70 0%, #4d7d52 60%, #335538 100%)'
              : 'radial-gradient(circle at 30% 30%, var(--td-blue-300) 0%, var(--td-blue) 55%, var(--td-blue-600) 100%)',
            color: '#fff',
            display: 'flex', alignItems: 'center', justifyContent: 'center',
            boxShadow: recording
              ? '0 10px 24px color-mix(in srgb, var(--td-orange) 40%, transparent), inset 0 -3px 8px rgba(0,0,0,0.2), inset 0 2px 4px rgba(255,255,255,0.2)'
              : '0 10px 24px color-mix(in srgb, var(--td-blue) 35%, transparent), inset 0 -3px 8px rgba(0,0,0,0.2), inset 0 2px 4px rgba(255,255,255,0.2)',
            transform: recording ? 'translateY(1px)' : 'translateY(0)',
            transition: 'background 200ms var(--ease-out), box-shadow 200ms var(--ease-out)',
            WebkitTapHighlightColor: 'transparent',
            touchAction: 'none', outline: 'none',
          }}>
          {recorded ? (
            <svg width="34" height="34" viewBox="0 0 24 24" fill="none" stroke="#fff" strokeWidth="2.2" strokeLinecap="round" strokeLinejoin="round">
              <path d="M20 6 9 17l-5-5"/>
            </svg>
          ) : (
            <svg width="34" height="34" viewBox="0 0 24 24" fill="none"
              stroke="#fff" strokeWidth="1.7" strokeLinecap="round" strokeLinejoin="round">
              <rect x="9" y="2" width="6" height="12" rx="3" fill="rgba(255,255,255,0.22)"/>
              <path d="M5 11a7 7 0 0 0 14 0"/>
              <path d="M12 18v3M9 21h6"/>
            </svg>
          )}
        </button>
      </div>
      <div style={{ flex: 1, minWidth: 0 }}>
        <div style={{
          fontFamily: fonts.native, fontSize: 14, fontWeight: 700,
          color: recording ? 'var(--td-orange)' : recorded ? '#4d7d52' : 'var(--td-navy)',
          lineHeight: 1.35,
        }}>
          {recording ? `${held} ${duration.toFixed(1)}s` :
           recorded  ? `Recorded · ${duration.toFixed(1)}s` :
           hint}
        </div>
        {recorded && (
          <button onClick={onClear} style={{
            marginTop: 6, padding: '4px 10px',
            background: 'transparent', border: '1px solid var(--border)',
            borderRadius: 'var(--radius-pill)',
            fontFamily: 'var(--font-sans)', fontSize: 11, fontWeight: 600,
            color: 'var(--fg2)', cursor: 'pointer',
            textTransform: 'uppercase', letterSpacing: '0.06em',
          }}>Re-record</button>
        )}
      </div>
    </div>
  );
}

// ──────────────────────────────────────────────────────────────────────────
// Role toggle — segmented (member / employee)
// ──────────────────────────────────────────────────────────────────────────

function RoleToggle({ value, onChange, memberLabel, employeeLabel, fonts }) {
  return (
    <div style={{
      display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 0,
      background: '#fff', border: '1px solid var(--border)',
      borderRadius: 'var(--radius-md)', padding: 4,
    }}>
      {[
        { val: 'member',   label: memberLabel,   sub: 'A member' },
        { val: 'employee', label: employeeLabel, sub: 'An employee' },
      ].map(opt => {
        const active = value === opt.val;
        return (
          <button key={opt.val} onClick={() => onChange(opt.val)}
            style={{
              padding: '12px 16px',
              background: active ? 'var(--td-blue)' : 'transparent',
              color: active ? '#fff' : 'var(--fg2)',
              border: 'none', borderRadius: 'var(--radius-sm)',
              cursor: 'pointer',
              fontFamily: fonts.native, fontSize: 15, fontWeight: 700,
              letterSpacing: fonts.cjk ? 0 : '-0.005em',
              transition: 'all 160ms var(--ease-out)',
              display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 2,
              WebkitTapHighlightColor: 'transparent',
            }}>
            {opt.label}
            <span style={{
              fontFamily: 'var(--font-sans)', fontSize: 10, fontWeight: 500,
              color: active ? 'rgba(255,255,255,0.78)' : 'var(--fg3)',
              textTransform: 'uppercase', letterSpacing: '0.08em',
            }}>{opt.sub}</span>
          </button>
        );
      })}
    </div>
  );
}

Object.assign(window, { FeedbackScreen });
