/* global React */
// The showcase interactive keyboard — auto-plays a typing demo with crystal ripples
function KeyboardDemo() {
  const t = window.theme;

  // Keyboard layout — QWERTY with Bopomofo overlays
  const rows = [
    [
      { en: '1', zh: 'ㄅ' }, { en: '2', zh: 'ㄉ' }, { en: '3', zh: 'ˇ' }, { en: '4', zh: 'ˋ' },
      { en: '5', zh: 'ㄓ' }, { en: '6', zh: 'ˊ' }, { en: '7', zh: '˙' }, { en: '8', zh: 'ㄚ' },
      { en: '9', zh: 'ㄞ' }, { en: '0', zh: 'ㄢ' }, { en: '-', zh: 'ㄦ' },
    ],
    [
      { en: 'q', zh: 'ㄆ' }, { en: 'w', zh: 'ㄊ' }, { en: 'e', zh: 'ㄍ' }, { en: 'r', zh: 'ㄐ' },
      { en: 't', zh: 'ㄔ' }, { en: 'y', zh: 'ㄗ' }, { en: 'u', zh: 'ㄧ' }, { en: 'i', zh: 'ㄛ' },
      { en: 'o', zh: 'ㄟ' }, { en: 'p', zh: 'ㄣ' },
    ],
    [
      { en: 'a', zh: 'ㄇ' }, { en: 's', zh: 'ㄋ' }, { en: 'd', zh: 'ㄎ' }, { en: 'f', zh: 'ㄑ' },
      { en: 'g', zh: 'ㄕ' }, { en: 'h', zh: 'ㄘ' }, { en: 'j', zh: 'ㄨ' }, { en: 'k', zh: 'ㄜ' },
      { en: 'l', zh: 'ㄠ' }, { en: ';', zh: 'ㄤ' },
    ],
    [
      { en: 'z', zh: 'ㄈ' }, { en: 'x', zh: 'ㄌ' }, { en: 'c', zh: 'ㄏ' }, { en: 'v', zh: 'ㄒ' },
      { en: 'b', zh: 'ㄖ' }, { en: 'n', zh: 'ㄙ' }, { en: 'm', zh: 'ㄩ' },
      { en: ',', zh: 'ㄝ' }, { en: '.', zh: 'ㄡ' }, { en: '/', zh: 'ㄥ' },
    ],
  ];

  // Demo sequence: types a 中英混打 phrase with ripples
  // Maps to final committed characters
  const sequence = [
    // "我" — ㄨㄛˇ = j+i+3
    { type: 'zh', keys: ['j', 'i', '3'], commit: '我', bopomofo: 'ㄨㄛˇ' },
    // "喜歡" — ㄒㄧˇ+ㄏㄨㄢ = vu3+cj84
    { type: 'zh', keys: ['v', 'u', '3'], commit: '喜', bopomofo: 'ㄒㄧˇ' },
    { type: 'zh', keys: ['c', 'j', '0'], commit: '歡', bopomofo: 'ㄏㄨㄢ' },
    // switch to english — "coffee"
    { type: 'en', keys: ['c', 'o', 'f', 'f', 'e', 'e'], commit: 'coffee' },
    { type: 'en', keys: [' '], commit: ' ' },
    // "和" — ㄏㄜˊ = cj6
    { type: 'zh', keys: ['c', 'k', '6'], commit: '和', bopomofo: 'ㄏㄜˊ' },
    // "bagel"
    { type: 'en', keys: ['b', 'a', 'g', 'e', 'l'], commit: 'bagel' },
    { type: 'en', keys: ['.'], commit: '。' },
  ];

  const [committed, setCommitted] = React.useState('');
  const [buffer, setBuffer] = React.useState('');
  const [pressed, setPressed] = React.useState(null);
  const [ripples, setRipples] = React.useState([]);
  const [seqIdx, setSeqIdx] = React.useState(0);
  const [keyIdx, setKeyIdx] = React.useState(0);
  const [mode, setMode] = React.useState('zh');
  const rippleId = React.useRef(0);

  React.useEffect(() => {
    const timer = setTimeout(() => {
      const step = sequence[seqIdx];
      if (!step) return;
      const key = step.keys[keyIdx];

      // Press animation
      setPressed(key);
      setMode(step.type);

      // Spawn ripple
      const id = ++rippleId.current;
      setRipples(r => [...r, { id, key }]);
      setTimeout(() => setRipples(r => r.filter(rp => rp.id !== id)), 900);

      // Update buffer
      if (step.type === 'zh') {
        setBuffer(b => b + (step.bopomofo && keyIdx === step.keys.length - 1 ? '' : key));
      } else {
        setBuffer(b => b + key);
      }

      setTimeout(() => setPressed(null), 180);

      // Advance
      const lastKey = keyIdx === step.keys.length - 1;
      if (lastKey) {
        setTimeout(() => {
          setCommitted(c => {
            const next = c + step.commit;
            return next.length > 20 ? '' : next;
          });
          setBuffer('');
          if (seqIdx === sequence.length - 1) {
            setTimeout(() => {
              setCommitted('');
              setSeqIdx(0);
              setKeyIdx(0);
            }, 1800);
          } else {
            setSeqIdx(i => i + 1);
            setKeyIdx(0);
          }
        }, 250);
      } else {
        setKeyIdx(i => i + 1);
      }
    }, keyIdx === 0 ? 500 : 260);
    return () => clearTimeout(timer);
  }, [seqIdx, keyIdx]);

  const candidates = React.useMemo(() => {
    const step = sequence[seqIdx];
    if (!step || step.type !== 'zh') return [];
    const sets = {
      '我': ['我', '窩', '倭'],
      '喜': ['喜', '洗', '璽', '徙'],
      '歡': ['歡', '還', '環', '緩'],
      '和': ['和', '合', '河', '核'],
    };
    return sets[step.commit] || [];
  }, [seqIdx]);

  return (
    <section id="demo" data-screen-label="04 Keyboard Demo" style={{
      position: 'relative', overflow: 'hidden',
      background: 'radial-gradient(ellipse 100% 80% at 50% 40%, #1E1E2C 0%, #0E0E1A 70%, #08080F 100%)',
      padding: '120px 40px',
    }}>
      {/* Ambient glow */}
      <div aria-hidden style={{
        position: 'absolute', top: '30%', left: '50%', transform: 'translateX(-50%)',
        width: 900, height: 500,
        background: 'radial-gradient(ellipse, rgba(155,127,255,0.25) 0%, rgba(74,159,255,0.15) 40%, transparent 70%)',
        filter: 'blur(80px)', pointerEvents: 'none',
      }} />

      <div style={{ maxWidth: 1100, margin: '0 auto', position: 'relative' }}>
        <div style={{ textAlign: 'center', marginBottom: 60 }}>
          <div style={{
            fontFamily: t.fontDisplay, fontSize: 12, fontWeight: 700,
            color: '#D0C5FF', letterSpacing: '0.14em', textTransform: 'uppercase',
            marginBottom: 18,
          }}>Try the Magic · 按鍵即發光</div>
          <h2 style={{
            fontFamily: t.fontDisplay, fontSize: 56, fontWeight: 700,
            lineHeight: 1.05, letterSpacing: '-0.03em', color: '#fff',
            margin: 0, marginBottom: 16, textWrap: 'balance',
          }}>
            每一次敲擊，都是一次<br />
            <span style={{
              background: t.gradSpectrum,
              WebkitBackgroundClip: 'text', backgroundClip: 'text',
              color: 'transparent', WebkitTextFillColor: 'transparent',
            }}>水晶光折射</span>。
          </h2>
          <p style={{
            fontFamily: t.fontBody, fontSize: 17, lineHeight: 1.6,
            color: '#9B9BAF', maxWidth: 560, margin: '0 auto',
          }}>看 ZingIME 自動在中英文之間切換，每一次按鍵都有即時的水晶漣漪回饋。</p>
        </div>

        {/* Output screen */}
        <div style={{
          background: 'rgba(255,255,255,0.03)',
          border: '1px solid rgba(255,255,255,0.08)',
          borderRadius: 20,
          padding: '24px 28px',
          marginBottom: 28,
          backdropFilter: 'blur(20px)',
          display: 'grid', gridTemplateColumns: '1fr auto', gap: 24, alignItems: 'center',
        }}>
          <div>
            <div style={{
              fontFamily: t.fontMono, fontSize: 10, color: '#5A5A6E',
              letterSpacing: '0.1em', textTransform: 'uppercase', marginBottom: 10,
            }}>Output</div>
            <div style={{
              fontFamily: t.fontBody, fontSize: 28, color: '#fff', lineHeight: 1.4,
              minHeight: 40, letterSpacing: '0.01em',
            }}>
              {committed || <span style={{ color: '#4A4A5E' }}>開始打字…</span>}
              {buffer && (
                <span style={{
                  fontFamily: t.fontMono, fontSize: 20,
                  color: mode === 'zh' ? t.lavender : t.rosePink,
                  textDecoration: 'underline', textDecorationColor: mode === 'zh' ? t.royalPurple : t.rosePink,
                  marginLeft: 4,
                }}>{buffer}</span>
              )}
              <span style={{
                display: 'inline-block', width: 2, height: 26, marginLeft: 3, verticalAlign: -4,
                background: t.skyBlue, animation: 'zing-blink 1s infinite',
              }} />
            </div>
          </div>
          <div style={{
            fontFamily: t.fontDisplay, fontSize: 11, fontWeight: 700,
            padding: '6px 14px', borderRadius: 999,
            background: mode === 'en' ? 'rgba(255,159,229,0.15)' : 'rgba(155,127,255,0.15)',
            color: mode === 'en' ? '#FF9FE5' : '#D0C5FF',
            letterSpacing: '0.12em',
            border: `1px solid ${mode === 'en' ? 'rgba(255,159,229,0.3)' : 'rgba(155,127,255,0.3)'}`,
          }}>{mode === 'en' ? 'EN 英文' : 'ZH 中文'}</div>
        </div>

        {/* Candidate bar */}
        <div style={{
          background: '#15151F', borderRadius: 16, padding: '14px 18px',
          border: '1px solid rgba(255,255,255,0.06)',
          marginBottom: 32, minHeight: 56,
          display: 'flex', alignItems: 'center', gap: 10,
          boxShadow: '0 12px 40px rgba(155,127,255,0.18)',
        }}>
          <span style={{
            fontFamily: t.fontMono, fontSize: 10, color: '#5A5A6E',
            letterSpacing: '0.1em', textTransform: 'uppercase', marginRight: 8,
          }}>候選</span>
          {candidates.length ? candidates.map((c, i) => (
            <div key={i} style={{
              fontFamily: t.fontBody, fontSize: 16,
              padding: '7px 14px', borderRadius: 10,
              background: i === 0 ? t.gradEnergetic : 'rgba(255,255,255,0.04)',
              color: '#fff',
              display: 'flex', alignItems: 'baseline', gap: 7,
              boxShadow: i === 0 ? '0 4px 16px rgba(74,159,255,0.35)' : 'none',
              transition: 'all 0.2s',
            }}>
              <span style={{
                fontFamily: t.fontMono, fontSize: 10,
                color: i === 0 ? 'rgba(255,255,255,0.7)' : t.mediumGray,
              }}>{i + 1}</span>
              {c}
            </div>
          )) : (
            <span style={{ fontFamily: t.fontBody, fontSize: 14, color: '#4A4A5E' }}>—</span>
          )}
        </div>

        {/* Keyboard */}
        <div style={{
          background: 'linear-gradient(180deg, rgba(30,30,44,0.9) 0%, rgba(14,14,26,0.95) 100%)',
          borderRadius: 20, padding: '20px 18px',
          border: '1px solid rgba(255,255,255,0.08)',
          boxShadow: '0 30px 80px rgba(0,0,0,0.5), inset 0 1px 0 rgba(255,255,255,0.06)',
          position: 'relative',
        }}>
          {rows.map((row, rIdx) => (
            <div key={rIdx} style={{
              display: 'flex', gap: 6, justifyContent: 'center',
              marginBottom: rIdx < 3 ? 6 : 0,
              paddingLeft: rIdx === 2 ? 14 : rIdx === 3 ? 28 : 0,
              paddingRight: rIdx === 2 ? 14 : rIdx === 3 ? 28 : 0,
            }}>
              {row.map(k => {
                const isPressed = pressed === k.en;
                const activeRipples = ripples.filter(r => r.key === k.en);
                return (
                  <div key={k.en} style={{
                    position: 'relative',
                    flex: '1 1 0', maxWidth: 72,
                    aspectRatio: '1 / 1',
                    borderRadius: 10,
                    background: isPressed
                      ? 'linear-gradient(135deg, rgba(144,213,255,0.4), rgba(208,197,255,0.5), rgba(255,207,255,0.4))'
                      : 'linear-gradient(180deg, rgba(255,255,255,0.06) 0%, rgba(255,255,255,0.02) 100%)',
                    border: isPressed
                      ? '1px solid rgba(208,197,255,0.6)'
                      : '1px solid rgba(255,255,255,0.06)',
                    boxShadow: isPressed
                      ? '0 0 24px rgba(208,197,255,0.6), 0 0 48px rgba(255,159,229,0.4), inset 0 1px 0 rgba(255,255,255,0.3)'
                      : 'inset 0 1px 0 rgba(255,255,255,0.06), 0 1px 2px rgba(0,0,0,0.2)',
                    display: 'flex', flexDirection: 'column',
                    alignItems: 'center', justifyContent: 'center', gap: 1,
                    transition: 'all 0.15s',
                    transform: isPressed ? 'translateY(2px)' : 'translateY(0)',
                    overflow: 'visible',
                  }}>
                    <div style={{
                      fontFamily: t.fontBody, fontSize: 11,
                      color: isPressed ? '#fff' : '#7070A0',
                      position: 'absolute', top: 5, left: 7,
                    }}>{k.zh}</div>
                    <div style={{
                      fontFamily: t.fontDisplay, fontSize: 15, fontWeight: 600,
                      color: isPressed ? '#fff' : '#B8B8C8',
                      position: 'absolute', bottom: 5, right: 7,
                    }}>{k.en}</div>
                    {/* Ripples */}
                    {activeRipples.map(r => (
                      <div key={r.id} aria-hidden style={{
                        position: 'absolute', inset: 0,
                        borderRadius: 10, pointerEvents: 'none',
                        background: 'radial-gradient(circle, rgba(255,255,255,0.5) 0%, rgba(208,197,255,0.4) 30%, rgba(255,159,229,0.2) 60%, transparent 75%)',
                        animation: 'zing-ripple 0.9s ease-out forwards',
                      }} />
                    ))}
                  </div>
                );
              })}
            </div>
          ))}
          {/* Spacebar row */}
          <div style={{ display: 'flex', gap: 6, justifyContent: 'center', marginTop: 6 }}>
            <div style={{
              flex: '0 0 60%', height: 38, borderRadius: 10,
              background: pressed === ' '
                ? 'linear-gradient(135deg, rgba(144,213,255,0.4), rgba(208,197,255,0.5))'
                : 'linear-gradient(180deg, rgba(255,255,255,0.06), rgba(255,255,255,0.02))',
              border: '1px solid rgba(255,255,255,0.06)',
              boxShadow: pressed === ' '
                ? '0 0 24px rgba(208,197,255,0.6)'
                : 'inset 0 1px 0 rgba(255,255,255,0.06)',
              fontFamily: t.fontMono, fontSize: 11, color: '#7070A0',
              display: 'flex', alignItems: 'center', justifyContent: 'center',
              transition: 'all 0.15s',
            }}>space</div>
          </div>
        </div>

        <div style={{
          textAlign: 'center', marginTop: 24,
          fontFamily: t.fontMono, fontSize: 12, color: '#5A5A6E',
          letterSpacing: '0.08em',
        }}>
          ↑ 自動播放示範 · 實際使用時，每一次按鍵都是即時反饋
        </div>
      </div>

      <style>{`
        @keyframes zing-ripple {
          0% { transform: scale(1); opacity: 1; }
          100% { transform: scale(2.5); opacity: 0; }
        }
      `}</style>
    </section>
  );
}
window.KeyboardDemo = KeyboardDemo;
