/* ===== 学习模式 · 加法 / 减法 操作台 ===== */
(function () {
  const { useState, useRef, useEffect, useCallback } = React;

  /* ---- 触控 / 点击 通用拖拽 hook(iPad 兼容) ---- */
  function useGridPointer(onIdx, onCommit) {
    const active = useRef(false);
    const fire = useCallback((e) => {
      const t = document.elementFromPoint(e.clientX, e.clientY);
      const cell = t && t.closest && t.closest('[data-idx]');
      if (cell) onIdx(parseInt(cell.dataset.idx, 10), cell);
    }, [onIdx]);
    return {
      onPointerDown: (e) => { active.current = true; try { e.currentTarget.setPointerCapture(e.pointerId); } catch (x) {} fire(e); },
      onPointerMove: (e) => { if (active.current) fire(e); },
      onPointerUp: () => { if (active.current && onCommit) onCommit(); active.current = false; },
      onPointerCancel: () => { active.current = false; },
      style: { touchAction: 'none' },
    };
  }
  window.useGridPointer = useGridPointer;

  /* ---- 圆角方块格 ---- */
  function Sq({ idx, fill, size, cross, glow }) {
    return (
      <div data-idx={idx} style={{
        width: size, height: size, borderRadius: 14,
        background: fill || 'rgba(74,59,107,.05)',
        boxShadow: fill
          ? 'inset -4px -5px 0 rgba(0,0,0,.13), inset 4px 4px 0 rgba(255,255,255,.4)'
          : 'inset 0 0 0 2px rgba(74,59,107,.10)',
        outline: glow ? '4px solid var(--yellow)' : 'none',
        outlineOffset: glow ? '1px' : 0,
        display: 'flex', alignItems: 'center', justifyContent: 'center',
        position: 'relative', transition: 'background .12s, outline .15s',
        cursor: 'pointer',
      }}>
        {cross && <span className="num" style={{ color: '#fff', fontSize: size * 0.62, lineHeight: 1, textShadow: '0 1px 0 rgba(0,0,0,.25)' }}>✕</span>}
      </div>
    );
  }
  window.Sq = Sq;

  /* ---- 大数字步进器 ---- */
  function Stepper({ label, value, min, max, onChange, color }) {
    const set = (d) => () => { Sound.click(); onChange(Math.max(min, Math.min(max, value + d))); };
    return (
      <div style={{ display: 'flex', alignItems: 'center', gap: 12 }}>
        {label && <span style={{ fontSize: 20, color: 'var(--ink-soft)' }}>{label}</span>}
        <button className="btn num" onClick={set(-1)} style={{ background: color, width: 52, height: 52, borderRadius: 16, fontSize: 32, padding: 0, lineHeight: 1 }}>−</button>
        <span className="num" style={{ fontSize: 38, minWidth: '1.5em', textAlign: 'center', color }}>{value}</span>
        <button className="btn num" onClick={set(1)} style={{ background: color, width: 52, height: 52, borderRadius: 16, fontSize: 30, padding: 0, lineHeight: 1 }}>+</button>
      </div>
    );
  }
  window.Stepper = Stepper;

  const COLS = 5, ROWS = 4, MAX = 20;
  const CELL = 60, GAP = 9;
  const gridW = COLS * CELL + (COLS - 1) * GAP;

  function GridBoard({ render, handlers }) {
    return (
      <div {...handlers} style={{ ...handlers.style, position: 'relative', padding: 12, background: '#fff',
        borderRadius: 22, boxShadow: 'inset 0 0 0 3px rgba(74,59,107,.08)' }}>
        {/* 满五 / 满十 参考线 */}
        <div style={{ position: 'absolute', left: 12, right: 12, top: `calc(12px + ${2 * CELL + GAP}px + ${GAP / 2 - 1.5}px)`,
          height: 4, borderRadius: 4, background: 'rgba(255,201,60,.85)', zIndex: 3, pointerEvents: 'none' }} />
        <div style={{ display: 'grid', gridTemplateColumns: `repeat(${COLS}, ${CELL}px)`,
          gridTemplateRows: `repeat(${ROWS}, ${CELL}px)`, gap: GAP }}>
          {render()}
        </div>
      </div>
    );
  }

  /* =================== 加法操作台 =================== */
  function AddLearn() {
    const [n, setN] = useState(3);       // 第一个数(红)
    const [total, setTotal] = useState(3); // 已填总数(红+蓝)
    const b = total - n;

    useEffect(() => { if (total < n) setTotal(n); }, [n]);

    const onIdx = (i) => {
      if (i < n) { setTotal(n); return; }     // 红区:清空蓝
      const nt = i + 1;
      if (nt !== total) { Sound.pop(); if (nt === 10 || nt === 20) Sound.correct(); }
      setTotal(nt);
    };
    const commit = () => {
      if (b > 0) {
        Sound.speak(`${n} 加 ${b} 等于 ${total}`);
        if (total === 20) Celebrate.balloons(8);
        if (total % 5 === 0) Celebrate.stars(12);
      }
    };
    const handlers = useGridPointer(onIdx, commit);

    const render = () => Array.from({ length: MAX }).map((_, i) => {
      let fill = null;
      if (i < n) fill = 'var(--pink)';
      else if (i < total) fill = 'var(--blue)';
      return <Sq key={i} idx={i} size={CELL} fill={fill} glow={(i === 9 || i === 19) && i < total} />;
    });

    return (
      <Pad
        controls={<Stepper label="先选第一个数" value={n} min={0} max={20} onChange={setN} color="var(--pink)" />}
        hint="👆 点一点 / 拖一拖后面的格子,加上去!"
        board={<GridBoard render={render} handlers={handlers} />}
        equation={<BigEq parts={[
          { t: n, c: 'var(--pink)' }, { t: '+', c: 'var(--ink-soft)' },
          { t: b, c: 'var(--blue)' }, { t: '=', c: 'var(--ink-soft)' },
          { t: total, c: 'var(--green)' },
        ]} />}
        onReset={() => { setN(3); setTotal(3); Sound.click(); }}
      />
    );
  }

  /* =================== 减法操作台 =================== */
  function SubLearn() {
    const [n, setN] = useState(12);          // 起始数(红)
    const [gone, setGone] = useState(() => new Set()); // 划掉的格

    useEffect(() => { setGone(new Set()); }, [n]);
    const b = [...gone].filter((i) => i < n).length;
    const left = n - b;

    const onIdx = (i) => {
      if (i >= n) return;
      setGone((prev) => {
        const s = new Set(prev);
        if (!s.has(i)) { s.add(i); Sound.pop(); } // 拿走时才出声,拖动不重复
        return s;
      });
    };
    const commit = () => { Sound.speak(`${n} 减 ${b} 等于 ${left}`); if (left === 0) Celebrate.stars(10); };
    const handlers = useGridPointer(onIdx, commit);

    const render = () => Array.from({ length: MAX }).map((_, i) => {
      const on = i < n;
      const x = gone.has(i);
      return <Sq key={i} idx={i} size={CELL} fill={on ? (x ? 'rgba(74,59,107,.22)' : 'var(--blue)') : null} cross={on && x} />;
    });

    return (
      <Pad
        controls={<Stepper label="一共有几个" value={n} min={1} max={20} onChange={setN} color="var(--blue)" />}
        hint="👆 点一点蓝格子,把它们拿走(打✕)!"
        board={<GridBoard render={render} handlers={handlers} />}
        equation={<BigEq parts={[
          { t: n, c: 'var(--blue)' }, { t: '−', c: 'var(--ink-soft)' },
          { t: b, c: 'var(--coral)' }, { t: '=', c: 'var(--ink-soft)' },
          { t: left, c: 'var(--green)' },
        ]} />}
        onReset={() => { setGone(new Set()); Sound.click(); }}
      />
    );
  }

  /* ---- 操作台外壳 ---- */
  function Pad({ controls, hint, board, equation, onReset }) {
    return (
      <div style={{ display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 18, padding: '4px 18px 30px' }}>
        <div className="card" style={{ padding: '14px 24px' }}>{controls}</div>
        <div style={{ fontSize: 19, color: 'var(--ink-soft)' }}>{hint}</div>
        <div style={{ display: 'flex', gap: 30, alignItems: 'center', flexWrap: 'wrap', justifyContent: 'center' }}>
          {board}
          <div style={{ display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 18 }}>
            {equation}
            <button className="pill" onClick={onReset} style={{ fontSize: 20 }}>🔄 重来</button>
          </div>
        </div>
      </div>
    );
  }

  function BigEq({ parts }) {
    return (
      <div className="num" style={{ display: 'flex', alignItems: 'center', gap: 14,
        fontSize: 'clamp(40px,7vw,68px)', lineHeight: 1, background: 'var(--paper)',
        padding: '18px 26px', borderRadius: 24, boxShadow: 'var(--shadow-sm)' }}>
        {parts.map((p, i) => (
          <span key={i} style={{ color: p.c, minWidth: typeof p.t === 'number' ? '0.7em' : 'auto', textAlign: 'center' }}>{p.t}</span>
        ))}
      </div>
    );
  }

  Object.assign(window, { AddLearn, SubLearn, GridBoard, Pad, BigEq });
})();
