/* ===== 学习模式 · 乘法面积模型 + 拆分线 ===== */
(function () {
  const { useState, useRef, useCallback } = React;

  const MAXN = 9, CELL = 46, GAP = 6, PITCH = CELL + GAP, PAD = 14;

  function MulLearn() {
    const [rows, setRows] = useState(3);
    const [cols, setCols] = useState(4);
    const [sp, setSp] = useState(3);          // 拆分线:左块列数
    const gridRef = useRef(null);
    const dragMode = useRef(null);            // 'size' | 'split'

    const clampSplit = (s, c) => Math.max(0, Math.min(c, s));

    /* ---- 在网格上拖动:确定 行×列 ---- */
    const sizeFromPoint = useCallback((e) => {
      const t = document.elementFromPoint(e.clientX, e.clientY);
      const cell = t && t.closest && t.closest('[data-rc]');
      if (!cell) return;
      const [r, c] = cell.dataset.rc.split('-').map(Number);
      setRows(r + 1); setCols((pc) => { const nc = c + 1; setSp((s) => clampSplit(s, nc)); return nc; });
    }, []);

    /* ---- 拖动拆分线 ---- */
    const splitFromPoint = useCallback((e) => {
      const g = gridRef.current; if (!g) return;
      const rect = g.getBoundingClientRect();
      const x = e.clientX - rect.left - PAD;
      let s = Math.round(x / PITCH);
      setCols((c) => { setSp(clampSplit(s, c)); return c; });
    }, []);

    const onDown = (e, mode) => {
      dragMode.current = mode;
      try { e.currentTarget.setPointerCapture(e.pointerId); } catch (x) {}
      if (mode === 'size') sizeFromPoint(e);
      else splitFromPoint(e);
      e.stopPropagation();
    };
    const onMove = (e) => {
      if (!dragMode.current) return;
      if (dragMode.current === 'size') sizeFromPoint(e);
      else splitFromPoint(e);
    };
    const onUp = () => {
      if (dragMode.current) { Sound.pop(); Sound.speak(koujue(rows, cols)); }
      dragMode.current = null;
    };

    const product = rows * cols;
    const leftA = rows * sp, rightA = rows * (cols - sp);
    const split = sp > 0 && sp < cols;

    const ORANGE = 'var(--orange)', PURPLE = 'var(--purple)';

    return (
      <div style={{ display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 16, padding: '4px 16px 30px' }}>
        <div className="card" style={{ padding: '12px 22px', display: 'flex', gap: 26, flexWrap: 'wrap', justifyContent: 'center' }}>
          <Stepper label="几行" value={rows} min={1} max={9} onChange={setRows} color="var(--purple)" />
          <Stepper label="几列" value={cols} min={1} max={9} onChange={(v) => { setCols(v); setSp((s) => clampSplit(s, v)); }} color="var(--mint)" />
        </div>
        <div style={{ fontSize: 19, color: 'var(--ink-soft)', textAlign: 'center', maxWidth: 560 }}>
          👆 在格子上拖出一个长方形 &nbsp;·&nbsp; 拖<b style={{ color: 'var(--yellow)' }}>黄色竖线</b>把它拆成两块好算的口诀
        </div>

        <div style={{ display: 'flex', gap: 28, alignItems: 'center', flexWrap: 'wrap', justifyContent: 'center' }}>
          {/* 网格 */}
          <div ref={gridRef}
            onPointerDown={(e) => onDown(e, 'size')} onPointerMove={onMove} onPointerUp={onUp} onPointerCancel={onUp}
            style={{ position: 'relative', padding: PAD, background: '#fff', borderRadius: 22,
              boxShadow: 'inset 0 0 0 3px rgba(74,59,107,.08)', touchAction: 'none' }}>
            <div style={{ display: 'grid', gridTemplateColumns: `repeat(${MAXN}, ${CELL}px)`,
              gridTemplateRows: `repeat(${MAXN}, ${CELL}px)`, gap: GAP }}>
              {Array.from({ length: MAXN * MAXN }).map((_, k) => {
                const r = Math.floor(k / MAXN), c = k % MAXN;
                const on = r < rows && c < cols;
                let fill = null;
                if (on) fill = split ? (c < sp ? ORANGE : PURPLE) : 'var(--purple)';
                return (
                  <div key={k} data-rc={`${r}-${c}`} style={{
                    width: CELL, height: CELL, borderRadius: 10,
                    background: fill || 'rgba(74,59,107,.05)',
                    boxShadow: fill
                      ? 'inset -3px -4px 0 rgba(0,0,0,.13), inset 3px 3px 0 rgba(255,255,255,.4)'
                      : 'inset 0 0 0 2px rgba(74,59,107,.08)',
                    transition: 'background .1s',
                  }} />
                );
              })}
            </div>
            {/* 拆分线手柄 */}
            {cols > 1 && (
              <div onPointerDown={(e) => onDown(e, 'split')} onPointerMove={onMove} onPointerUp={onUp} onPointerCancel={onUp}
                style={{ position: 'absolute', top: PAD - 6, height: rows * PITCH - GAP + 12,
                  left: PAD + sp * PITCH - GAP / 2 - 11, width: 22, cursor: 'ew-resize',
                  display: 'flex', justifyContent: 'center', touchAction: 'none', zIndex: 4 }}>
                <div style={{ width: 5, height: '100%', background: 'var(--yellow)', borderRadius: 5,
                  boxShadow: '0 0 0 2px #fff' }} />
                <div className="num" style={{ position: 'absolute', bottom: -2, transform: 'translateY(100%)',
                  background: 'var(--yellow)', color: '#fff', borderRadius: 10, padding: '2px 10px', fontSize: 17,
                  boxShadow: 'var(--shadow-sm)', whiteSpace: 'nowrap' }}>拖我 ↔</div>
              </div>
            )}
          </div>

          {/* 结果区 */}
          <div style={{ display: 'flex', flexDirection: 'column', gap: 14, alignItems: 'center', width: 300, flexShrink: 0 }}>
            <div className="num" style={{ fontSize: 'clamp(30px,4.4vw,46px)', background: 'var(--paper)',
              padding: '14px 20px', borderRadius: 22, boxShadow: 'var(--shadow-sm)', textAlign: 'center', whiteSpace: 'nowrap' }}>
              <span style={{ color: 'var(--purple)' }}>{rows}</span>
              <span style={{ color: 'var(--ink-soft)' }}> × </span>
              <span style={{ color: 'var(--mint)' }}>{cols}</span>
              <span style={{ color: 'var(--ink-soft)' }}> = </span>
              <span style={{ color: 'var(--green)' }}>{product}</span>
            </div>
            <div className="num" style={{ fontSize: 22, color: 'var(--pink)' }}>{koujue(rows, cols)}</div>

            {split && (
              <div className="card pop-in" style={{ padding: '14px 18px', textAlign: 'center', width: '100%' }}>
                <div style={{ fontSize: 17, color: 'var(--ink-soft)', marginBottom: 8 }}>拆成两块好算啦:</div>
                <div className="num" style={{ fontSize: 25, lineHeight: 1.5, whiteSpace: 'nowrap' }}>
                  <span style={{ color: ORANGE }}>{rows}×{sp}={leftA}</span>
                  <span style={{ color: 'var(--ink-soft)' }}> + </span>
                  <span style={{ color: PURPLE }}>{rows}×{cols - sp}={rightA}</span>
                </div>
                <div className="num" style={{ fontSize: 24, marginTop: 6, color: 'var(--green)', whiteSpace: 'nowrap' }}>
                  {leftA} + {rightA} = {product}
                </div>
              </div>
            )}
            <button className="pill" onClick={() => { Sound.click(); setRows(3); setCols(4); setSp(3); }} style={{ fontSize: 20 }}>🔄 重来</button>
          </div>
        </div>
      </div>
    );
  }

  Object.assign(window, { MulLearn });
})();
