// add.jsx — 记一笔：收/支切换 + 分类 + 数字键盘
// 作为底部弹层使用：传入 onClose 时顶部显示关闭按钮，记好后自动收起。
function AddScreen({ onSave, onClose }) {
  const [type, setType] = React.useState('expense');
  const [cat, setCat] = React.useState('toy');
  const [amount, setAmount] = React.useState('0');
  const [note, setNote] = React.useState('');
  const [saved, setSaved] = React.useState(false);

  const cats = type === 'income' ? INCOME_CATS : EXPENSE_CATS;

  const switchType = (t) => {
    setType(t);
    setCat(t === 'income' ? 'allowance' : 'toy');
  };

  const tap = (d) => {
    setAmount((a) => {
      if (d === '.') return a.includes('.') ? a : a + '.';
      if (a === '0') return d;
      if (a.replace('.', '').length >= 5) return a;
      return a + d;
    });
  };
  const back = () => setAmount((a) => (a.length <= 1 ? '0' : a.slice(0, -1)));

  const num = parseFloat(amount) || 0;
  const canSave = num > 0;

  const doSave = () => {
    if (!canSave) return;
    onSave({ type, cat, amount: num, note: note.trim() || (CATS[cat] || {}).label });
    setSaved(true);
    setTimeout(() => {
      setSaved(false); setAmount('0'); setNote('');
      if (onClose) onClose(); // 弹层模式：记好后自动收起
    }, 1100);
  };

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

  return (
    <div className="screen add">
      <div className="add-head">
        <h2 className="screen-title">记一笔</h2>
        {onClose && <button className="add-close" onClick={onClose} aria-label="关闭">✕</button>}
      </div>

      {/* 收/支切换 */}
      <div className="seg">
        <button className={'seg-btn income' + (type === 'income' ? ' on' : '')} onClick={() => switchType('income')}>
          <IconUp size={18} /> 存进来
        </button>
        <button className={'seg-btn expense' + (type === 'expense' ? ' on' : '')} onClick={() => switchType('expense')}>
          <IconDown size={18} /> 花出去
        </button>
      </div>

      {/* 金额显示 */}
      <div className={'amt-display ' + type}>
        <span className="amt-sign">{type === 'income' ? '+' : '−'}</span>
        <Coin size={34} />
        <span className="amt-num">{amount}</span>
      </div>

      {/* 分类 */}
      <div className="cat-grid">
        {cats.map((c) => (
          <button key={c} className={'cat-cell' + (cat === c ? ' on' : '')} onClick={() => setCat(c)}>
            <CatIcon id={c} size={38} />
            <span>{CATS[c].label}</span>
          </button>
        ))}
      </div>

      {/* 备注 */}
      <input className="note-input" placeholder="写点什么…（可不填）"
        value={note} maxLength={20} onChange={(e) => setNote(e.target.value)} />

      {/* 键盘 */}
      <div className="num-pad">
        {keys.map((k, i) => {
          if (k === 'del') return (
            <button key={i} className="num-key fn" onClick={back}><IconDelete size={24} /></button>
          );
          return <button key={i} className="num-key" onClick={() => tap(k)}>{k}</button>;
        })}
      </div>

      <button className={'save-btn ' + type + (canSave ? '' : ' disabled') + (saved ? ' done' : '')}
        onClick={doSave} disabled={!canSave}>
        {saved ? <><IconCheck size={22} /> 记好啦！</> : <>记下这一笔</>}
      </button>
    </div>
  );
}
window.AddScreen = AddScreen;
