// lock.jsx — 密码锁屏（PIN 键盘）
function LockScreen({ onUnlock, theme, onToggleTheme }) {
  const [pin, setPin] = React.useState('');
  const [shake, setShake] = React.useState(false);
  const [wrong, setWrong] = React.useState(false);
  const [checking, setChecking] = React.useState(false);

  React.useEffect(() => {
    if (pin.length !== 6 || checking) return;
    setChecking(true);
    const t = setTimeout(async () => {
      let ok = false;
      try { ok = await apiLogin(pin); } catch (e) {}
      if (ok) {
        onUnlock();
      } else {
        setShake(true); setWrong(true);
        setTimeout(() => { setShake(false); setPin(''); }, 480);
      }
      setChecking(false);
    }, 160);
    return () => clearTimeout(t);
  }, [pin]);

  const press = (d) => {
    if (checking) return;
    setWrong(false);
    setPin((p) => (p.length >= 6 ? p : p + d));
  };
  const del = () => setPin((p) => p.slice(0, -1));

  const keys = ['1', '2', '3', '4', '5', '6', '7', '8', '9', '', '0', 'del'];

  return (
    <div className="screen lock">
      <ThemeToggle theme={theme} onToggle={onToggleTheme} />
      <div className="lock-top">
        <Penguin size={132} mood={wrong ? 'think' : 'happy'} glow />
        <h1 className="lock-title">嗨，欢迎回来！</h1>
        <p className="lock-sub">{wrong ? '密码不对，再试一次哦～' : '输入家庭密码解锁'}</p>
      </div>

      <div className={'pin-dots' + (shake ? ' shake' : '')}>
        {[0, 1, 2, 3, 4, 5].map((i) => (
          <span key={i} className={'pin-dot' + (i < pin.length ? ' filled' : '') + (wrong ? ' bad' : '')} />
        ))}
      </div>

      <div className="keypad">
        {keys.map((k, i) => {
          if (k === '') return <span key={i} className="key key-empty" />;
          if (k === 'del') return (
            <button key={i} className="key key-fn" onClick={del} aria-label="删除">
              <IconDelete size={28} />
            </button>
          );
          return (
            <button key={i} className="key" onClick={() => press(k)}>{k}</button>
          );
        })}
      </div>

      <p className="lock-hint">提示：初始密码 <b>1234</b></p>
    </div>
  );
}
window.LockScreen = LockScreen;
