// home.jsx — 首页：余额大卡 + 时间段小结 + 明细
function Stat({ kind, value }) {
  const isIn = kind === 'income';
  return (
    <div className={'stat ' + kind}>
      <div className="stat-ic">{isIn ? <IconUp size={18} /> : <IconDown size={18} />}</div>
      <div className="stat-body">
        <div className="stat-label">{isIn ? '收入' : '支出'}</div>
        <div className="stat-val"><Coin size={15} style={{ marginRight: 3 }} />{value}</div>
      </div>
    </div>
  );
}

function TxRow({ t }) {
  const cat = CATS[t.cat] || CATS.other;
  const isIn = t.type === 'income';
  return (
    <div className="tx-row">
      <CatIcon id={t.cat} size={40} />
      <div className="tx-main">
        <div className="tx-note">{t.note || cat.label}</div>
        <div className="tx-meta">{cat.label} · {timeLabel(t.ts)}</div>
      </div>
      <div className={'tx-amt ' + (isIn ? 'in' : 'out')}>
        {isIn ? '+' : '−'}{t.amount}
        <Coin size={15} style={{ marginLeft: 2 }} />
      </div>
    </div>
  );
}

// 余额卡右侧的小企鹅：
//   单击 → 轻轻一抖(1.5s)；
//   双击 → 放大+大幅抖动，约 2s 后回落静止；
//   持续连点 → 一直保持放大+大幅抖动（幅度恒定），停手后才回落。
const TAP_WINDOW = 250; // 单/双击判定窗口(ms)，窗口内出现第二击即判为双击
const HOLD_MS = 1500;   // 最后一次点击后保持摆动的时长（+回落 0.5s ≈ 双击共 2s）
const SETTLE_MS = 500;  // 回落过渡时长
function BalancePet() {
  const { useState, useRef, useEffect } = React;
  const [anim, setAnim] = useState('');     // '' | 'wiggle' | 'active'
  const imgRef = useRef(null);
  const tap = useRef({ wait: null, hold: null, end: null, settling: false });

  useEffect(() => () => { // 卸载时清掉所有挂起的定时器
    clearTimeout(tap.current.wait);
    clearTimeout(tap.current.hold);
    clearTimeout(tap.current.end);
  }, []);

  // 停手 → 从「当前这一帧的真实姿态」平滑过渡回原大小、静止（不跳跃）
  function settleDown() {
    const el = imgRef.current;
    setAnim(''); // 移除 active 类，停止循环关键帧
    if (!el) return;
    tap.current.settling = true;
    const reduce = window.matchMedia && window.matchMedia('(prefers-reduced-motion: reduce)').matches;
    if (reduce) { el.style.cssText = ''; tap.current.settling = false; return; }
    const cur = getComputedStyle(el).transform; // 定格当前的旋转+缩放矩阵
    el.style.animation = 'none';
    el.style.transition = 'none';
    el.style.transform = (cur && cur !== 'none') ? cur : 'scale(1)';
    void el.offsetWidth;                         // 强制重排，锁定起点姿态
    el.style.transition = 'transform ' + SETTLE_MS + 'ms cubic-bezier(.25,.85,.35,1)';
    el.style.transform = 'scale(1) rotate(0deg)';
    clearTimeout(tap.current.end);
    tap.current.end = setTimeout(() => {
      el.style.animation = ''; el.style.transition = ''; el.style.transform = '';
      tap.current.settling = false;
    }, SETTLE_MS);
  }

  // 进入/维持「放大大幅摆动」，并把回落时间顺延到最后一次点击之后
  function keepActive() {
    const el = imgRef.current;
    if (el) { el.style.animation = ''; el.style.transition = ''; el.style.transform = ''; } // 清掉残留的回落过渡
    tap.current.settling = false;
    clearTimeout(tap.current.end);
    setAnim('active');
    clearTimeout(tap.current.hold);
    tap.current.hold = setTimeout(settleDown, HOLD_MS);
  }

  function handleTap() {
    if (anim === 'active' || tap.current.settling) { keepActive(); return; } // 连点/回落中：续命
    if (tap.current.wait) {            // 窗口内的第二击 → 进入摆动状态
      clearTimeout(tap.current.wait);
      tap.current.wait = null;
      keepActive();
    } else {                          // 第一击，等判定窗口确认是不是单击
      tap.current.wait = setTimeout(() => {
        tap.current.wait = null;
        setAnim('wiggle');            // 单击轻抖
        clearTimeout(tap.current.end);
        tap.current.end = setTimeout(() => setAnim(''), 1500);
      }, TAP_WINDOW);
    }
  }

  return (
    <div className="bc-pet">
      <img ref={imgRef} className={'bc-pet-img' + (anim ? ' ' + anim : '')}
        src="app/penguin.png" alt="金币小企鹅" draggable="false"
        onClick={handleTap} />
    </div>
  );
}

function HomeScreen({ tx, range, setRange, balance, onGoAdd, theme, onToggleTheme }) {
  const sum = summarize(tx, range);
  const sorted = tx.filter((t) => inRange(t.ts, range)).sort((a, b) => b.ts - a.ts);
  const rangeLabel = (RANGES.find((r) => r.id === range) || {}).label || '';
  const hour = new Date().getHours();
  const greet = hour < 11 ? '早上好呀！' : hour < 18 ? '下午好呀！' : '晚上好呀！';

  return (
    <div className="screen home">
      <div className="home-head">
        <div>
          <div className="greet">{greet}</div>
          <div className="greet-sub">你的金币管家在这儿</div>
        </div>
        <div className="head-right">
          <ThemeToggle theme={theme} onToggle={onToggleTheme} />
          <Penguin size={56} mood="wink" />
        </div>
      </div>

      {/* 余额大卡 */}
      <div className="balance-card">
        <div className="bc-glow" />
        <div className="bc-label">我现在有</div>
        <div className="bc-amount">
          <Coin size={46} />
          <span className="bc-num">{balance}</span>
          <span className="bc-unit">金币</span>
        </div>
        <BalancePet />
      </div>

      {/* 时间段 */}
      <div className="range-bar">
        {RANGES.map((r) => (
          <button key={r.id}
            className={'range-chip' + (range === r.id ? ' on' : '')}
            onClick={() => setRange(r.id)}>{r.label}</button>
        ))}
      </div>

      {/* 小结 */}
      <div className="summary">
        <Stat kind="income" value={sum.income} />
        <Stat kind="expense" value={sum.expense} />
        <div className="stat net">
          <div className="stat-label">结余</div>
          <div className="stat-val net-val">
            {sum.net >= 0 ? '+' : '−'}{Math.abs(sum.net)}
            <Coin size={16} style={{ marginLeft: 2 }} />
          </div>
        </div>
      </div>

      {/* 明细 */}
      <div className="list-head">
        <span>最近记录</span>
        <button className="link-btn" onClick={onGoAdd}>+ 记一笔</button>
      </div>
      <div className="tx-list">
        {sorted.length === 0 && <div className="empty">{rangeLabel}还没有记录，去记一笔吧！</div>}
        {sorted.map((t) => <TxRow key={t.id} t={t} />)}
      </div>
    </div>
  );
}
window.HomeScreen = HomeScreen;
